當前位置:成語大全網 - 英語詞典 - python中列表如何去重

python中列表如何去重

1、利用字典的fromkeys()和keys()方法。

#列表去重

L =[1,2,3,4,5,6,6,5,4,3,2,1]

#創建壹個空字典

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])

L = list(L)

print(L) #[1,2,3,4,5,6]

#可以用列表的sort()方法排序,默認是升序

# print(L.sort())

L.sort(reverse=True) #升序

print(L)#[6,5,4,3,2,1]

print('--------------------------')

2、集合,集合是可叠代的

L2 = [1,2,3,4,5,6,6,5,4,3,2,1]

L2 = set(L2)

print(L2) #{1,2,3,4,5,6}

L2 = list(L2)

print(L2) #[1,2,3,4,5,6]

print('-------------------------------')

3、用for循環

L3 = [1,2,3,4,5,6,6,5,4,3,2,1]

L4 = []

for x in L3:

if x not in L4:

L4.append(x)

print(L4) #[1,2,3,4,5,6]