首页 > 代码库 > 【算法】两个数组字符串去重追加

【算法】两个数组字符串去重追加

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);	}}

 

【算法】两个数组字符串去重追加