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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章