去重的四种方法
#方法一
AList = [1, 2, 3, 1, 2]
print(list(set(AList)))
lists = []
while len(AList)!=0:
num = AList.pop()
if num not in lists:
lists.append(num)
print(lists)
#方法二
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)
#方法三
import numpy as np
lists = [1,1,2,3,4,6,9,6,2,2]
lists = np.unique(lists)
print(list(lists))
#方法四
#列表去重
L = [1,2,3,4,5,6,6,5,4,3,2,1]
#第一种方法,利用字典的fromkeys()和keys()方法
#创建一个空字典
d = {}
#用字典的fromkeys()方法去重,得到一个字典,去重之后的元素为键,值为None的字典
#{1: None, 2: None, 3: None, 4: None, 5: None, 6: None}
#fromkeys(iterable,value=None)
L = d.fromkeys(L)
print(L) #{1: None, 2: None, 3: None, 4: None, 5: None, 6: None}
#用字典的keys()方法得到一个类似列表的东西,但不是列表。keys()函数返回的是一个dict_keys对象:
#以字典的键作为元素的一个类列表
L = L.keys()
print(L) #dict_keys([1, 2, 3, 4, 5, 6])