【问题标题】:How to iterate through a bunch of values in a dictionaries that are lists python如何遍历列表中的字典中的一堆值python
【发布时间】:2020-01-31 17:06:56
【问题描述】:

ratinglist = open("ratings.txt").readlines()

booklist = open("booklist.txt").readlines()

keys = [key.strip('\n') for key in ratinglist[0::2]]

values = [value.strip(' \n').split(' ') for value in ratinglist[1::2]]


my_dict = dict(zip(keys, values))


for values in my_dict:
    value * x = sum

所以,我有一个巨大的字典,其中包含每个键的值列表。

这是我的字典的一个例子:

'KeeLed': ['0', '0', '0', '5', '0', '0', '0', '5', '0', '5', '5', '0', '0', '0', '0', '0', '5', '-3', '-3', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '0', '5', '0', '0', '5', '0', '5', '5', '5', '5', '0', '0', '0', '0', '0', '3', '1', '0', '0', '0', '0'], 'Megan': ['5', '5', '0', '0', '0', '0', '0', '0', '0', '3', '0', '5', '0', '0', '1', '0', '5', '0', '1', '5', '0', '0', '0', '0', '0', '1', '0', '5', '0', '0', '3', '5', '5', '0', '0', '5', '0', '0', '3', '0', '0', '3', '5', '5', '0', '0', '0', '0', '0', '5', '5', '0', '5', '0', '0']}

我需要做的是做一个 for 循环,循环遍历每个值,将它们相乘,然后相加。

我只需要帮助让 for 循环正确地遍历值。

例如,对于 KeeLed 和 Megan,我希望这个 for 循环遍历它们各自的值列表,然后将它们相乘,然后相加。

像这样:0 * 5, + 5 * 0, + 0 * 0, + 5 * 0.... 等等

问题是我在网上没有找到任何关于如何遍历 dictionary 中的列表的信息。我找到了一些关于遍历列表的资源,但我需要遍历字典中的值列表。

我希望将结果放在一个列表中,但如果我在 for 循环方面获得一些帮助,我可以这样做。

scores for each person = [325, 450]

【问题讨论】:

  • 如果我理解正确,你想要的列表[1, 2, 3, 4]output = 1*2 + 3*4 = 14
  • 您不会获得有关每种功能组合的教程。列表是 dict 值这一事实无关紧要:您知道如何从 dict 中获取值;你知道如何遍历列表。按顺序将它们放在一起。

标签: python arrays dictionary


【解决方案1】:

“问题是我在网上没有找到任何关于如何迭代字典中的列表的信息。我找到了一些关于循环列表的资源,但我需要循环遍历那些值的列表在字典里面。”

示例

myDict = {

'KeeLed': ['0', '0', '0', '5', '0', '0', '0', '5', '0', '5', '5', '0', '0', '0', '0', '0', '5', '-3', '-3', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '0', '5', '0', '0', '5', '0', '5', '5', '5', '5', '0', '0', '0', '0', '0', '3', '1', '0', '0', '0', '0'], 
'Megan': ['5', '5', '0', '0', '0', '0', '0', '0', '0', '3', '0', '5', '0', '0', '1', '0', '5', '0', '1', '5', '0', '0', '0', '0', '0', '1', '0', '5', '0', '0', '3', '5', '5', '0', '0', '5', '0', '0', '3', '0', '0', '3', '5', '5', '0', '0', '0', '0', '0', '5', '5', '0', '5', '0', '0']

}

# For-looping through dict will give the key.
for name in myDict:

  total = 0

  # applying the key into myDict will give the list associated with the dict
  for score in myDict[name]:

    total = total + int(score)

  print(name,total)

结果

KeeLed 54
Megan 85

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-07
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 2012-07-04
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    相关资源
    最近更新 更多