【广州python】list去重的各种方法

python 未结 0 32
南京网站优化
南京网站优化 2021-05-28 08:40
悬赏:83
最简单的思路就是:


  • id = [1,2,3,3,4,2,3,4,5,6,2]
  • news_id = []
  • for id in id:
  •     if id not in news_id:
  •         news_id.append(id)
  • print news_id
是用set:



  • id = [1,4,3,3,4,2,3,4,5,6,2]
  • id = list(set(id))

按照索引再次排序:


  • id = [1,4,3,3,4,2,3,4,5,6,2]
  • news_id = list(set(id))
  • news_id.sort(key=id.index)




使用itertools.grouby,但是列表顺序会变:



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


用reduce:


  • id = [1,4,3,3,4,2,3,4,5,6,2]
  • func = lambda x,y: y in x and x or x+[y]
  • reduce(func, [[], ] + id)







              思路其实就是先把ids变为[[], 1,4,3,......] ,然后在利用reduce的特性


相关标签:
回答
  • 消灭零回复
提交回复