成人在线亚洲_国产日韩视频一区二区三区_久久久国产精品_99国内精品久久久久久久

您的位置:首頁技術(shù)文章
文章詳情頁

Python list去重且保持原順序不變的方法

瀏覽:87日期:2022-06-23 14:24:48
背景

python 去重一頓操作猛如虎,set list 扒拉下去,就去重了,但是順序就打亂了。如果對順序沒有需要的話,這樣確實(shí)沒有什么所謂。但是如果需要保留順序的話,就需要一點(diǎn)小小的改變。

code && demo

list 去重,順序亂掉

# normal 寫法l1 = [’b’,’c’,’d’,’b’,’c’,’a’,’a’]l2 = list(set(l1))print(l2)# plus 寫法l1 = [’b’,’c’,’d’,’b’,’c’,’a’,’a’]l2 = {}.fromkeys(l1).keys()

去重后還是原 list 順序

# normal 寫法l1 = [’b’,’c’,’d’,’b’,’c’,’a’,’a’]l2 = list(set(l1))l2.sort(key=l1.index)# plus 寫法l1 = [’b’,’c’,’d’,’b’,’c’,’a’,’a’]l2 = sorted(set(l1),key=l1.index)

寫循環(huán)代碼實(shí)現(xiàn)

# normal 寫法l1 = [’b’,’c’,’d’,’b’,’c’,’a’,’a’]l2 = []for i in l1: if not i in l2: l2.append(i) # plus 寫法l1 = [’b’,’c’,’d’,’b’,’c’,’a’,’a’]l2 = [][l2.append(i) for i in l1 if not i in l2]

寫 while 循環(huán)代碼實(shí)現(xiàn)

L = [3, 1, 2, 1, 3, 4]T = L[:]for i in L: while T.count(i) > 1: del T[T.index(i)]T.sort(key=L.index)

lambda 寫法

備注:

ambda L,i: L if i in L else L + [i] # 如果元素在列表中,那么返回列表本身,不在的話 L + [i] [[],] + L # 等價(jià)于 [[], L],方便后面計(jì)算 總結(jié)

如果糾結(jié)空間復(fù)雜度的,用 python 干啥?先談能不能完成,再談優(yōu)化吧。

以上就是Python list去重且保持原順序不變的方法的詳細(xì)內(nèi)容,更多關(guān)于Python list去重的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!

標(biāo)簽: Python 編程
相關(guān)文章: