這篇文章主要介紹了python中對list去重的多種方法,現在分享給大家,需要的朋友可以參考下
今天遇到一個問題,在同事隨意的提示下,用了itertools.groupby 這個函數。不過這個東西最後還是沒用。
問題就是對一個list中的新聞id進行去重,去重之後要保證順序不變。
直覺式方法
最簡單的想法就是:
複製程式碼 程式碼如下:
ids = [1,2,3,3,4,2,3,4,5,6,1] news_ids = [] for id in ids: if id not in news_ids: news_ids.append(id) print news_ids
這樣也可行,但是看起來不夠爽。
用set
另外一個解決方案就是用set:
複製程式碼 程式碼如下:
ids = [1,4,3,3,4,2,3,4,5,6,1] ids = list(set(ids))
這樣的結果是沒有維持原來的順序。
依照索引再次排序
最後透過這種方式解決:
複製程式碼 程式碼如下:
ids = [1,4,3,3,4,2,3,4,5,6,1] news_ids = list(set(ids)) news_ids.sort(ids.index)
使用itertools.grouby
文章一開始就提到itertools.grouby, 如果不考慮列表順序的話可用這個:
#複製程式碼 程式碼如下:
ids = [1,4,3,3,4,2,3,4,5,6,1] ids.sort() it = itertools.groupby(ids) for k, g in it: print k
關於itertools.groupby的原理可以看這裡:http://docs.python.org/2/library/itertools.html#itertools.groupby
網友補充:用reduce
網友reatlk留言給了另外的解決方案。我補充並解釋到這裡:
複製程式碼 程式碼如下:
In [5]: ids = [1,4,3,3,4,2,3,4,5,6,1] In [6]: func = lambda x,y:x if y in x else x + [y] In [7]: reduce(func, [[], ] + ids) Out[7]: [1, 4, 3, 2, 5, 6]
上面是我在ipython中運行的程式碼,其中的lambda x,y:x if y in x else x [y] 等價於lambda x,y: y in x and x or x [y] 。
想法其實就是先把ids變成[[], 1,4,3,......] ,然後在利用reduce的特性。 reduce解釋參考這裡:http://docs.python.org/2/library/functions.html#reduce
以上是python中對list去重的幾種方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

pythonlistscanStoryDatatepe,ArrayModulearRaysStoreOneType,and numpyArraySareSareAraysareSareAraysareSareComputations.1)列出sareversArversAtileButlessMemory-Felide.2)arraymoduleareareMogeMogeNareSaremogeNormogeNoreSoustAta.3)

WhenyouattempttostoreavalueofthewrongdatatypeinaPythonarray,you'llencounteraTypeError.Thisisduetothearraymodule'sstricttypeenforcement,whichrequiresallelementstobeofthesametypeasspecifiedbythetypecode.Forperformancereasons,arraysaremoreefficientthanl

pythonlistsarepartofthestAndArdLibrary,herilearRaysarenot.listsarebuilt-In,多功能,和Rused ForStoringCollections,而EasaraySaraySaraySaraysaraySaraySaraysaraySaraysarrayModuleandleandleandlesscommonlyusedDduetolimitedFunctionalityFunctionalityFunctionality。

ThescriptisrunningwiththewrongPythonversionduetoincorrectdefaultinterpretersettings.Tofixthis:1)CheckthedefaultPythonversionusingpython--versionorpython3--version.2)Usevirtualenvironmentsbycreatingonewithpython3.9-mvenvmyenv,activatingit,andverifying

Pythonarrayssupportvariousoperations:1)Slicingextractssubsets,2)Appending/Extendingaddselements,3)Insertingplaceselementsatspecificpositions,4)Removingdeleteselements,5)Sorting/Reversingchangesorder,and6)Listcomprehensionscreatenewlistsbasedonexistin

NumPyarraysareessentialforapplicationsrequiringefficientnumericalcomputationsanddatamanipulation.Theyarecrucialindatascience,machinelearning,physics,engineering,andfinanceduetotheirabilitytohandlelarge-scaledataefficiently.Forexample,infinancialanaly

useanArray.ArarayoveralistinpythonwhendeAlingwithHomoGeneData,performance-Caliticalcode,orinterfacingwithccode.1)同質性data:arraysSaveMemorywithTypedElements.2)績效code-performance-calitialcode-calliginal-clitical-clitical-calligation-Critical-Code:Arraysofferferbetterperbetterperperformanceformanceformancefornallancefornalumericalical.3)

不,notalllistoperationsareSupportedByArrays,andviceversa.1)arraysdonotsupportdynamicoperationslikeappendorinsertwithoutresizing,wheremactsperformance.2)listssdonotguaranteeconecontanttanttanttanttanttanttanttanttanttimecomplecomecomplecomecomecomecomecomecomplecomectacccesslectaccesslecrectaccesslerikearraysodo。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

Safe Exam Browser
Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

記事本++7.3.1
好用且免費的程式碼編輯器

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。

SublimeText3漢化版
中文版,非常好用

EditPlus 中文破解版
體積小,語法高亮,不支援程式碼提示功能