[英]Converting a list into a dictionary with multiple values using loops
我有一個字符串元素列表
marks = ["Bill, 50, 70, 90, 65, 81", "Jack, 80, 95, 100, 98, 72"]
我想使用一個循環,以便我可以擁有一個看起來像的字典
dictionary= {'Bill': [50,70,90, 65, 81] , 'Jack': [80,95,100, 98, 72]}
這些值也應該變成浮動值,因為我想找到平均值但我還沒有到那里。
這是我到目前為止:
dictionary ={}
for items in marks:
c = items.split(', ')
for a in range(len(c)):
dictionary[c[0]] = c[a]
print(dictionary)
它打印{'Bill': '81' , 'Jack': '72'}
這里的問題是我的字典中的每個鍵只有一個值,它是列表的最后一個值,我理解這是因為dictionary[c[0]]= c[a]
只是替換了前一個值。
我該怎么做才能讓鍵可以獲得多個值,而不會在循環中更改每個先前的值?
如果循環在執行此操作時效率低下,請告訴我,但這是我目前唯一喜歡的方法。
謝謝!
dictionary[c[0]] = c[a]
因此,只有最后一個值被添加到列表中。 為了添加所有值,您需要使用append()
。 要轉換為浮點數,請使用float()
。 更正的代碼:
dictionary ={}
for items in marks:
c = items.split(', ')
dictionary[c[0]] = []
for a in range(len(c)):
dictionary[c[0]].append(float(c[a]))
print(dictionary)
使用以下方法打開密鑰可能很容易:
key, *rest = items.split(', ')
這將使您可以按照您認為合適的方式處理rest
的其余項目(列表理解是一種特別的 Pythonic 方式)並完全避免索引和for
循環:
marks = ["Bill, 50, 70, 90, 65, 81", "Jack, 80, 95, 100, 98, 72"]
d = {}
for s in marks:
key, *rest = s.split(', ')
d[key] = [float(n) for n in rest]
留給你:
{'Bill': [50.0, 70.0, 90.0, 65.0, 81.0],
'Jack': [80.0, 95.0, 100.0, 98.0, 72.0]}
marks = ["Bill, 50, 70, 90, 65, 81", "Jack, 80, 95, 100, 98, 72"]
out = {name: [*map(int, grades)] for name, *grades in map(lambda m: m.split(','), marks)}
print(out)
印刷:
{'Bill': [50, 70, 90, 65, 81], 'Jack': [80, 95, 100, 98, 72]}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.