Chinaunix首页 | 论坛 | 博客
  • 博客访问: 159785
  • 博文数量: 27
  • 博客积分: 97
  • 博客等级: 民兵
  • 技术积分: 314
  • 用 户 组: 普通用户
  • 注册时间: 2012-11-19 19:34
个人简介

非攻飞攻,夜尽天明!

文章分类

全部博文(27)

文章存档

2014年(6)

2013年(21)

我的朋友

分类: LINUX

2013-10-03 09:41:32

    在一个列表中找出重复的值,返回不是重复的值  。这样的例子有很多。

    那么如何以集合返回呢?

    一开始想到,在定义两个列表A,B ,从给的列表中存值入列表A中,如果有重复的值,就一个入B中。

    后来发现python2.7中有个计数功能的 函数 Counter ,在加上字典,终于写好了“找出一个列表中重复的值“ 的这个题目。

#vim find_dups.py


  1 #!/usr/bin/python2.7                      #需要python2.7以上的才有函数Counter
  2                            
  3 import collections                            #导入含有Counter函数的模块
  4                            
  5 def find_dups(L):          
  6         '''find out that occur two or more times in the list. '''
  7         
  8         num = collections.Counter(L)    
  9
 10 #       invert the dictionary   对字典进行反相操作
 11         freq = {}          
 12         for (name,times) in num.items():
 13                 if times in freq:               
 14                         freq[times].append(name)        
 15                 else:      
 16                         freq[times] = [name]            
 17
 18 #       print              
 19         numname = set([])  
 20         print "the occur two or more times is:"
 21         for key in sorted(freq):        
 22                 for name in freq[key]:          
 23                         if key >= 2:                    
 24                                 numname.add(name)               
 25         print numname   




>>>from find_dups  import *
>>>L =[1,1,1,2,3,3,4,4,4,6,7,8,9,9]
>>>find_dups(L)
the occur two or more times is:
set([9, 3, 4, 1])


    
    
阅读(5841) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~