這篇文章主要介紹了Python程式設計對清單中字典元素進行排序的方法,涉及Python針對列表及字典元素的遍歷、讀取、轉換相關操作技巧,需要的朋友可以參考下
本文實例講述了Python程式設計對清單中字典元素進行排序的方法。分享給大家供大家參考,具體如下:
內容目錄:
#1. 問題起源
2. 對列表中的字典元素排序
3. 比較json(忽略列表中字典的順序)
#一、問題起源
##json物件a,b
a = '{"ROAD": [{"id": 123}, {"name": "no1"}]}' b = '{"ROAD": [{"name": "no1"}, {"id": 123}]}'特點:a,b對應的Python的物件中鍵對應的鍵值-清單中包含著相同的字典元素,但是唯一不同的是順序不同。如果忽略順序,如何判斷兩個json是否相等。因為字典本身是自己按鍵排序的,列表是按加入的順序排序的,如果對列表中的字典元素進行排序就可以輕鬆地排序了。如果列表中是普通的元素(不是字典),則透過
list(set())組合可以讀取列表進行排序,而列表中如果是字典元素不能使用list(set ())組合,看提示:
>>> a = [{'a':1, 'b':2}, {'c':3}] >>> a [{'a': 1, 'b': 2}, {'c': 3}] >>> b = set(a) Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> b = set(a) TypeError: unhashable type: 'dict'提示為字典是不可進行哈希操作的類型(普通非字典的元素進行哈希操作即可輕鬆排好序)。 那麼問題的本質即:如何對列表中的字典元素排序。
二、對列表中的字典元素排序
#還好,列表有>>> p = [{'b': 2}, {'a': 1, 'c': 3}] >>> q = [{'a': 1, 'c': 3}, {'b': 2}] >>> p [{'b': 2}, {'a': 1, 'c': 3}] >>> q [{'a': 1, 'c': 3}, {'b': 2}] >>> pp = sorted(p) >>> qq = sorted(q) >>> pp [{'b': 2}, {'a': 1, 'c': 3}] >>> qq [{'b': 2}, {'a': 1, 'c': 3}] >>> pp == qq True >>> p == q False可以看出,ok的,並且可以看出排序的原則是元素個數。
三、對json進行比較(忽略列表中字典的順序)
import json def compare_json(a, b): aa = json.loads(a) bb = json.loads(b) len_a = len(aa) len_b = len(bb) if len_a != len_b: return False else: for key in aa: if not bb.has_key(key): return False else: if sorted(aa[key]) != sorted(bb[key]): return False return True if name == "main": a = '{"ROAD": [{"id": 123}, {"name": "no1"}]}' b = '{"ROAD": [{"name": "no1"}, {"id": 123}]}' print compare_json(a, b)細節:自己寫json格式時,a = "{'road':1}" json.loads(a) 錯誤,得寫成a = '{"road:1}' 【單引號在外】
以上是Python程式設計如何對清單中字典元素進行排序的方法詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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。

toAccesselementsInapythonlist,useIndIndexing,負索引,切片,口頭化。 1)indexingStartSat0.2)否定indexingAccessesessessessesfomtheend.3)slicingextractsportions.4)iterationerationUsistorationUsisturessoreTionsforloopsoreNumeratorseforeporloopsorenumerate.alwaysCheckListListListListlentePtotoVoidToavoIndexIndexIndexIndexIndexIndExerror。

Arraysinpython,尤其是Vianumpy,ArecrucialInsCientificComputingfortheireftheireffertheireffertheirefferthe.1)Heasuedfornumerericalicerationalation,dataAnalysis和Machinelearning.2)Numpy'Simpy'Simpy'simplementIncressionSressirestrionsfasteroperoperoperationspasterationspasterationspasterationspasterationspasterationsthanpythonlists.3)inthanypythonlists.3)andAreseNableAblequick

你可以通過使用pyenv、venv和Anaconda來管理不同的Python版本。 1)使用pyenv管理多個Python版本:安裝pyenv,設置全局和本地版本。 2)使用venv創建虛擬環境以隔離項目依賴。 3)使用Anaconda管理數據科學項目中的Python版本。 4)保留系統Python用於系統級任務。通過這些工具和策略,你可以有效地管理不同版本的Python,確保項目順利運行。

numpyarrayshaveseveraladagesoverandastardandpythonarrays:1)基於基於duetoc的iMplation,2)2)他們的aremoremoremorymorymoremorymoremorymoremorymoremoremory,尤其是WithlargedAtasets和3)效率化,效率化,矢量化函數函數函數函數構成和穩定性構成和穩定性的操作,製造


熱AI工具

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

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

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

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

熱門文章

熱工具

DVWA
Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

WebStorm Mac版
好用的JavaScript開發工具

Atom編輯器mac版下載
最受歡迎的的開源編輯器

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

MinGW - Minimalist GNU for Windows
這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。