Python list去重且保持原順序不變的方法
python 去重一頓操作猛如虎,set list 扒拉下去,就去重了,但是順序就打亂了。如果對順序沒有需要的話,這樣確實沒有什么所謂。但是如果需要保留順序的話,就需要一點小小的改變。
code && demolist 去重,順序亂掉
# 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)代碼實現(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)代碼實現(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 # 等價于 [[], L],方便后面計算 總結(jié)如果糾結(jié)空間復雜度的,用 python 干啥?先談能不能完成,再談優(yōu)化吧。
以上就是Python list去重且保持原順序不變的方法的詳細內(nèi)容,更多關(guān)于Python list去重的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. python爬蟲實戰(zhàn)之制作屬于自己的一個IP代理模塊2. python 基于Appium控制多設(shè)備并行執(zhí)行3. python 實現(xiàn)圍棋游戲(純tkinter gui)4. 解決ajax請求后臺,有時收不到返回值的問題5. Python編寫nmap掃描工具6. .NET6打包部署到Windows Service的全過程7. .Net Core和RabbitMQ限制循環(huán)消費的方法8. HTML 絕對路徑與相對路徑概念詳細9. python 利用toapi庫自動生成api10. python實現(xiàn)PolynomialFeatures多項式的方法
