码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2016-11-04 16:37:51      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:new   book   util   set   link   atl   循环   pytho   stat   

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

 

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

标签:new   book   util   set   link   atl   循环   pytho   stat   

原文地址:http://www.cnblogs.com/baiboy/p/6030381.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!