算法两个数组字符串去重追加
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了算法两个数组字符串去重追加相关的知识,希望对你有一定的参考价值。
1 数组去重
python实现
#调用内置函数去重 def func(str): len1=len(str) len2=len(list(set(str))) print("去重后的结果是:",list(set(str)),"\t去重个数是:",(len1-len2)) #for 循环去重 def func1(str): nums=[] for n in str: if n not in nums: nums.append(n) print("去重后的结果是:",sorted(nums),"\t去重个数是:",(len(str)-len(nums))) # while去重 def func2(str): len1=len(str) for n in str: while str.count(n)>1: del str[str.index(n)] print("去重后的结果是:",sorted(str),"\t去重个数是:",(len1-len(str))) str=[1,3,2,4,2,4,1,6,4,5] func2(str)
字典去重
#调用内置函数去重 def func(str): len1=len(str.values()) len2=len(list(set(str.values()))) print("去重后的结果是:",list(set(str.values())),"\t去重个数是:",(len1-len2)) #for 循环去重 def func1(str): nums=[] for n in str.values(): if n not in nums: nums.append(n) print("去重后的结果是:",sorted(nums),"\t去重个数是:",(len(str.values())-len(nums))) str=[1,3,2,4,2,4,1,6,4,5] dirc={1:1,2:2,3:3,4:3} func2(dirc)
字符串追加去重排序
#调用内置函数去重 def func(str1,str2): print("去重后的结果是:",sorted(set(str1+str2)),"\t去重个数是:",(len(str1+str2)-len(set(str1+str2)))) #for 循环去重 def func1(str1,str2): nums=[] str=str1+str2 for n in str: if n not in nums: nums.append(n) print("去重后的结果是:",sorted(nums),"\t去重个数是:",(len(str)-len(nums))) # while去重 def func2(str1,str2): str=str1+str2 for n in str: while str.count(n)>1: del str[str.index(n)] print("去重后的结果是:",sorted(str),"\t去重个数是:",(len(str1+str2)-len(str))) str1=[‘很好‘,‘不错‘,‘很好‘,‘Very‘,‘Book‘,‘I‘,‘Love‘,‘I‘] str2=[‘Java‘,‘C#‘,‘Python‘,‘C#‘] func2(str1,str2)
Java实现
import java.util.LinkedList; import java.util.List; public class func { public static void unique(String[] str){ // array_unique List<String> list = new LinkedList<String>(); for(int i = 0; i < str.length; i++) { if(!list.contains(str[i])) { list.add(String.valueOf(str[i])); } } System.out.print("去重后的结果:"+list+"\t 共去重个数:"+(str.length-list.size())); } public static void main(String[] args){ String[] str={"1","3","2","4","2","4","1","6","4","5"}; unique(str); } }
set实现
import java.util.HashSet; import java.util.Set; public class func { public static void unique(String[] str){ Set<String> set = new HashSet<String>(); for (int i=0; i<str.length; i++) { set.add(str[i]); } System.out.print("去重后的结果:"+set+"\t 共去重个数:"+(str.length-set.size())); } public static void main(String[] args){ String[] str={"Python","SQL","C#","Java","C","Python","R","Matlab","C++","SQL"}; unique(str); } }
以上是关于算法两个数组字符串去重追加的主要内容,如果未能解决你的问题,请参考以下文章