繁体   English   中英

使用循环将列表转换为具有多个值的字典

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM