我有一個串列,里面有一些字典。該串列如下所示:
files = [
{'name': "text.txt", 'size': 10, 'location': "cloud", 'info': "Nothing"},
{'name': "img.jpg", 'size': 200, 'location': "local", 'info': "private"},
{'name': "cars.txt", 'size': 109, 'location': "cloud", 'info': "private"}
]
我還有一個“text.txt”、“img.jpg”和“cars.txt”所在的檔案夾。不知何故,我必須獲取“位置”為“云”且“資訊”為“無”的所有元素。
對資料進行排序的唯一方法是使用“next”函式
next((item for item in files if item["location"] == "cloud"), None)
實作這一目標的最快方法是什么?還要按“位置”和“資訊”排序?
uj5u.com熱心網友回復:
方法之一是這個
list(filter(lambda x: x["location"]=="cloud" and x["info"]=="Nothing",files))
# [{'name': 'text.txt', 'size': 10, 'location': 'cloud', 'info': 'Nothing'}]
如果您只想要名稱:
list(map(lambda x: x["name"], filter(lambda x: x["location"]=="cloud" and x["info"]=="Nothing",files)))
# ['text.txt']
uj5u.com熱心網友回復:
使用串列理解,只需遍歷字典并獲取名稱。
files = [dic['name'] for dic in files if dic['location'] == 'cloud' and dic['info'] == "Nothing"])
print(files)
輸出:
['text.txt']
uj5u.com熱心網友回復:
我將借此機會為jmespath插入一個插件,這是我最喜歡的用于處理結構化資料的 Python 包之一。
jmespath語言定義了一種路徑語法,用于定位嵌入在 JSON 檔案中的資訊(通過 json.load(s) 創建)。
在你的情況下,解決方案是。
In [3]: jmespath.search("[?location == 'cloud' && info == 'Nothing'].name", files)
Out[3]: ['text.txt']
查詢可以提前編譯。
In [4]: my_search = jmespath.compile("[?location == 'cloud' && info == 'Nothing'].name")
In [5]: my_search.search(files)
Out[5]: ['text.txt']
花在學習路徑語言上的時間很快就會得到回報。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/527664.html
標籤:Python列表排序字典
上一篇:如何按值從字典中洗掉鍵
