【问题标题】:How to iterate a key over a list of lists in a dictionary? [closed]如何在字典中的列表列表上迭代一个键? [关闭]
【发布时间】:2020-01-05 03:01:14
【问题描述】:

我现在对此有点困惑。我想获取一个键列表并在列表列表中迭代它

tests = ['test 1', 'test 2', 'test 3']
scores = [[90, 70, 60], [40, 50, 100], [60, 65, 90], [30, 61, 67], 
[80, 79, 83], [70, 97, 100]]

预期结果:

我想返回一个显示以下内容的字典:

'test 1': 90,'test 2' : 70, 'test 3': 60, 'test 1': 40, 'test 2': 50, 
'test 3': 100... 'test 1' : 70, 'test 2' : 97, 'test 3':100

测试 1:得分 1

测试 2:得分 2

测试 3:得分 3

【问题讨论】:

  • 欢迎来到 SO。请使用tour 并花时间阅读How to Ask 以及该页面上的其他链接。这不是讨论论坛或教程服务。您应该花一些时间通过the Tutorial 练习这些示例。它将向您介绍 Python 为解决您的问题所提供的工具。
  • dictionary that shows the following: - 这不是一个有效的 Python 字典(重复键)。

标签: python dictionary nested


【解决方案1】:

dictzip 一起使用:

[dict(zip(tests, score)) for score in scores]

输出:

[{'test 1': 90, 'test 2': 70, 'test 3': 60},
 {'test 1': 40, 'test 2': 50, 'test 3': 100},
 {'test 1': 60, 'test 2': 65, 'test 3': 90},
 {'test 1': 30, 'test 2': 61, 'test 3': 67},
 {'test 1': 80, 'test 2': 79, 'test 3': 83},
 {'test 1': 70, 'test 2': 97, 'test 3': 100}]

【讨论】:

  • 这正是我想要的。谢谢。但是,我注意到很多人说字典不能包含重复的键。我对此有点困惑,因为您创建的内容仍被视为字典。
  • @Jacky 实际上是一个字典列表,显示的结果包含五个字典的列表。其中每一个都包含唯一键“test 1”、“test 2”、“test 3”。
  • 正如@DarrylG 所指出的,这不是单个字典。单个字典不能包含重复的键。如果你必须有一个字典,我建议你接受@Ajax1234 的回答。
【解决方案2】:

字典不能包含重复的键,但是,您可以使用元组列表:

tests = ['test 1', 'test 2', 'test 3']
scores = [[90, 70, 60], [40, 50, 100], [60, 65, 90], [30, 61, 67], [80, 79, 83], [70, 97, 100]]
result = [(a, b) for i in scores for a, b in zip(tests, i)]

输出:

[('test 1', 90), ('test 2', 70), ('test 3', 60), ('test 1', 40), ('test 2', 50), ('test 3', 100), ('test 1', 60), ('test 2', 65), ('test 3', 90), ('test 1', 30), ('test 2', 61), ('test 3', 67), ('test 1', 80), ('test 2', 79), ('test 3', 83), ('test 1', 70), ('test 2', 97), ('test 3', 100)]

更好的方法是按目标键对整数进行分组:

from collections import defaultdict
d = defaultdict(list)
for i in scores:
   for a, b in zip(tests, i):
      d[a].append(b)

print(dict(d))

输出:

{'test 1': [90, 40, 60, 30, 80, 70], 'test 2': [70, 50, 65, 61, 79, 97], 'test 3': [60, 100, 90, 67, 83, 100]}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-22
    • 2011-05-09
    • 2019-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多