python学习——python对list去重的各种方法

原文链接 :https://www.the5fire.com/python-remove-duplicates-in-list.html

直观方法

最简单的思路就是:


  
  
  1. ids = [ 1 , 2 , 3 , 3 , 4 , 2 , 3 , 4 , 5 , 6 , 1 ]
  2. news_ids = []
  3. for id in ids :
  4. if id not in news_ids :
  5. news_ids . append ( id )
  6. print news_ids

这样也可行,但是看起来不够爽。

用set

另外一个解决方案就是用set:


  
  
  1. ids = [ 1 , 4 , 3 , 3 , 4 , 2 , 3 , 4 , 5 , 6 , 1 ]
  2. ids = list ( set ( ids ))

这样的结果是没有保持原来的顺序。

按照索引再次排序

最后通过这种方式解决:


  
  
  1. ids = [ 1 , 4 , 3 , 3 , 4 , 2 , 3 , 4 , 5 , 6 , 1 ]
  2. news_ids = list ( set ( ids ))
  3. news_ids . sort ( key = ids . index ) # 感谢网友:@Magic 指正。

使用itertools.grouby

文章一开始就提到itertools.grouby, 如果不考虑列表顺序的话可用这个:


  
  
  1. ids = [ 1 , 4 , 3 , 3 , 4 , 2 , 3 , 4 , 5 , 6 , 1 ]
  2. ids . sort ()
  3. it = itertools . groupby ( ids )
  4. for k , g in it :
  5. print k

关于itertools.groupby的原理可以看这里:http://docs.python.org/2/library/itertools.html#itertools.groupby

网友补充:用reduce

网友reatlk留言给了另外的解决方案。我补充并解释到这里:


  
  
  1. In [ 5 ]: ids = [ 1 , 4 , 3 , 3 , 4 , 2 , 3 , 4 , 5 , 6 , 1 ]
  2. In [ 6 ]: func = lambda x , y : x if y in x else x + [ y ]
  3. In [ 7 ]: reduce ( func , [[], ] + ids )
  4. Out [ 7 ]: [ 1 , 4 , 3 , 2 , 5 , 6 ]

上面是我在ipython中运行的代码,其中的 lambda x,y:x if y in x else x + [y] 等价于 lambda x,y: y in x and x orx+[y] 。

思路其实就是先把ids变为[[], 1,4,3,......] ,然后在利用reduce的特性。reduce解释参看这里: http://docs.python.org/2/library/functions.html#reduce
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值