Python對列表去重的多種方法 四種方法

2022-10-04 20:42:19 字數 1036 閱讀 3742

開發中對陣列、列表去重是非常常見的需求,對乙個list中的id進行去重,有程式設計客棧下面幾種方法,前面兩種方法不能保證順序, 後面兩種方法可以保持原來的順序。

下面的**都在python3下測試通過, python2下請自行測試

1. 使用set的特型,python的set和其他語言類似, 是乙個無序不重複元素集

orglist = [1,0,3,7,7,5]

#list()方法是把字串str或元組轉成陣列

formatlist = list(set(orglist))

print (formatlist)

結果:[0, 1, 3, 5, 7]

2. 使用keys()方法

orglist = [1,0,3,7,7,5]

#lisnsomnt()方法是把字串snsomntr或元組轉成陣列

formatlist = list({}.fromkeys(orglist).keys())

print (formatlist)

結果:[0, 1, 3, 5, 7]

上面兩種方法的問題是:結果是沒有保持原來的順序。

3. 迴圈遍曆法

orglist = [1,0,3,7,7,5]

formatlist =

for id in orglist:

if id not in formatlist:

formatlist.append(id)

print (formatlist)

結果:[1, 0, 3, 7, 5]

but,這樣的**不夠簡潔,不夠高階

4. 按照索引再次排序

orglist = [1,0,3,7,7,5]

formatlist = list(set(orglist))

formatlist.sort(key=orglist.index)

print (formatlist)

結果:nsomn[1, 0, 3, 7, 5]

總結本文標題: python對列表去重的多種方法(四種方法)

本文位址:

python 多表去重 Python列表去重

無聊統計了下列表去重到底有多少種方法。1.集合 list set alist 如果要保持順序 import random if name main a random.randint 0,10 for i in xrange 10 b list set a b.sort key a.index 2.字...

Python列表去重

標題有語病,其實是這樣的 假設有兩個列表 l1 1,2,3,4 l2 1,2,5,6 然後去掉l1中包含的l2的元素 直接這樣當然是不行的 def removeexists l1,l2 for e1 in l1 if e1 in l2 l1.remove e1 不管什麼語言都不能這麼幹,但是又有一點...

Python 對列表中的字典進行去重

from functools import reduce data list run function lambda x,y x if y in x else x y reduce run function,data list reduce函式為python內建函式 reduce function,...