溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Python對list去重的各種方法

發(fā)布時間:2020-07-17 09:14:16 來源:網(wǎng)絡(luò) 閱讀:545 作者:jedi911 欄目:編程語言

參考原文:https://www.the5fire.com/python-remove-duplicates-in-list.html

需求:去list進行去重,去重后保證順序不變

方法1:for循環(huán)

ids = [1, 2, 3, 3, 4, 2, 3, 4, 5, 6, 1]
new_ids = []

for id in ids:
    if id not in new_ids:
        new_ids.append(id)

print("new_ids==>", new_ids)

方法2:set

ids = [1,4,3,3,4,2,3,4,5,6,1]
new_ids = list(set(ids))

print(new_ids)

測試發(fā)現(xiàn)去重后不能保證原來的順序

方法3:按照索引再次排序

ids = [1, 4, 3, 3, 4, 2, 3, 4, 5, 6, 1]
new_ids = list(set(ids))
new_ids.sort(key=ids.index)

print(new_ids)

方法4:用reduce

ids = [1,4,3,3,4,2,3,4,5,6,1]
func = lambda x,y:x if y in x else x + [y]
reduce(func, [[], ] + ids)
[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變?yōu)閇[], 1,4,3,......] ,然后在利用reduce的特性

reduce()函數(shù)介紹

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI