![](/img/trans.png)
[英]Pythonic way to write create dictionary from dict comprehension, + something else
[英]Pythonic way to create a dictionary of lists (dict comprehension)
我有以下列表:
files = ['AAA_1', 'BBB_2', 'CCC_1', 'AAA_2', 'BBB_4']
我有以下聽寫:
dict = {
'AAA' : [],
'BBB': [],
'CCC' : []
}
我的預期輸出是:
dict = {
'AAA' : ['AAA_1', 'AAA_2'],
'BBB': ['BBB_2', 'BBB_4'],
'CCC' : ['CCC_1']
}
我能夠使用以下方法實現這一目標:
for file in files:
if file.startswith(file[:-2]):
dict[file[:-2]].append(file)
如果我使用:
dict = {file[:-2]: [file] for file in files if file.startswith(file[:-2])}
我有:
{'AAA': ['AAA_2'], 'BBB': ['BBB_4'], 'CCC': ['CCC_1']}
我的疑問是:如何使用字典理解在列表字典中附加值?
我不建議使用字典理解,因為簡單的 for 循環結構更具可讀性。 但如果你必須有一個,你去:
sorted_files = {f[:-2] : [file for file in files if file.startswith(f[:-2])] for f in files}
另外,我不建議使用 Python 關鍵字作為變量名。 這是不好的做法,有時您可能會混淆程序。
輸出:
{'AAA': ['AAA_1', 'AAA_2'], 'BBB': ['BBB_2', 'BBB_4'], 'CCC': ['CCC_1']}
你可以用這樣的兩個嵌套推導來做到這一點:
dict = {key: [file for file in files if file[:-2] == key] for key in dict}
如果你想純粹用推導來做到這一點,你需要一個內部列表推導來為給定的前綴構建整個列表,並且你可能需要另一個推導來構建前綴/鍵集(盡管這不是絕對必要的,因為你可以多次重新生成每個條目,它只會覆蓋自己):
>>> files = ['AAA_1', 'BBB_2', 'CCC_1', 'AAA_2', 'BBB_4']
>>> {k: [f for f in files if f.startswith(k)] for k in {f[:3] for f in files}}
{'BBB': ['BBB_2', 'BBB_4'], 'AAA': ['AAA_1', 'AAA_2'], 'CCC': ['CCC_1']}
請注意,除了不太易讀之外,它的效率也較低,因為您需要為每個條目遍歷整個files
。 使用循環遍歷files
一次是我將使用的方法。
您只需要使用嵌套理解:
dict_ = {
file_group[:-2]: [file for file in files if file.startswith(file_group[:-2])] for file_group in files}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.