怎么快速的對列表進行去重呢,去重之后原來的順序會不會改變呢?
1.以下的幾種情況結果是一樣的,去重之后順序會改變:
ids = [1,2,3,3,4,2,3,4,5,6,1]
news_ids = []
for id in ids:
if id not in news_ids:
news_ids.append(id)
print news_ids
或用set
ids = [1,4,3,3,4,2,3,4,5,6,1]
ids = list(set(ids))
或使用itertools.grouby
import itertools
ids = [1,4,3,3,4,2,3,4,5,6,1]
ids.sort()
it = itertools.groupby(ids)
for k, g in it:
print k
關於itertools.groupby的原理可以看這里:(1) http://docs.python.org/2/library/itertools.html#itertools.groupby
(2) https://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/001415616001996f6b32d80b6454caca3d33c965a07611f000
2.怎么能不改變原來的順序呢?(要用到reduce 關於reduce的介紹 http://docs.python.org/2/library/functions.html#reduce)
關於lambda的文章:http://www.cnblogs.com/nyist-xsk/p/7404675.html
關於reduce的文章: (1) http://www.cnblogs.com/XXCXY/p/5180245.html
(2) http://www.pythoner.com/46.html
In [5]: ids = [1,4,3,3,4,2,3,4,5,6,1]
In [6]: func = lambda x,y:x if y in x else x + [y]
In [7]: reduce(func, [[], ] + ids)
Out[7]: [1, 4, 3, 2, 5, 6]
其中的 lambda x,y:x if y in x else x + [y] 等價於 lambda x,y: y in x and x or x+[y] 。
思路其實就是先把ids變為[[], 1,4,3,......] ,然后在利用reduce的特性.
去列表去重,不改變原來的順序,還可以使用一個空列表把原列表里面不重復的數據"裝起來",例如:
list2 = []
list1 = [1,2,3,2,2,2,4,6,5]
for i in list1:
if i not in list2:
list2.append(i)
list2
[1, 2, 3, 4, 6, 5]
或者使用刪除元素索引的方法對列表去重,並且不改變原列表的順序
# python for刪除的時候會往前移(垃圾回收機制),未遍歷到的后一個占了前一個被刪除的"位置",導致這個數不會被遍歷到,而使最后的結果錯誤
# 局部變量在棧內存中存在,當for循環語句結束,那么變量會及時被gc(垃圾回收器)及時的釋放掉,不浪費空間;
# 如果使用循環之后還想去訪問循環語句中控制那個變量,使用while循環。
# 所以使用while循環刪除nums中的Val(的下標)
nums = [1,2,3,3,4,2,3,4,5,6,1]
val = 3
while val in nums:
nums.pop(nums.index(val))
print nums
return len(nums)