我正在嘗試從字串串列創建嵌套字典。字串的每個索引對應一個鍵,而每個字符對應一個值。
我有一個清單:
list = ['game', 'club', 'party', 'play']
我想創建一個(嵌套的)字典:
dict = {0: {'g', 'c', 'p', 'p'}, 1: {'a', 'l', 'a', 'l'}, 2: {'m', 'u', 'r', 'a'}, etc.}
我在想一些事情:
res = {}
for item in range(len(list)):
for i in list[item]:
if i not in res:
# create a key (index - ex. '0') and a value (character - ex. 'g' of 'game')
else:
# put the value in the corresponding key (ex. 'c' of 'club')
print(res)
uj5u.com熱心網友回復:
注意:您不能擁有具有重復值的集合。相反,創建一個字典,其中值是串列或元組:
from itertools import zip_longest
lst = ["game", "club", "party", "play"]
out = {
i: [v for v in t if not v is None] for i, t in enumerate(zip_longest(*lst))
}
print(out)
印刷:
{
0: ["g", "c", "p", "p"],
1: ["a", "l", "a", "l"],
2: ["m", "u", "r", "a"],
3: ["e", "b", "t", "y"],
4: ["y"],
}
uj5u.com熱心網友回復:
Andrejs 解決方案肯定是更優雅的解決方案。但是為了更接近您提出的解決方案,您可以這樣做:
items = ['game', 'club', 'party', 'play']
result = {}
for item in items:
for (idx, char) in enumerate(list(item)):
if idx not in result:
result[idx] = [char]
else:
result[idx].append(char)
print(result)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/535841.html
標籤:Python细绳列表字典
下一篇:根據條件將元素串列到字典
