【问题标题】:How can you construct a dictionary from lists of keys and data?如何从键和数据列表中构造字典?
【发布时间】:2020-10-26 14:49:21
【问题描述】:

我有以下 3 个列表:

names = ["paul", "saul", "steve", "chimpy"]
ages = [28, 59, 22, 5]
scores = [59, 85, 55, 60]

我需要将它们转换成这样的字典:

{'steve': [22, 55, 'fail'], 'saul': [59, 85, 'pass'], 'paul': [28, 59, 'fail'], 'chimpy': [5, 60, 'pass']}

'pass' 和 'fail' 来自分数 >=60 与否。

我可以通过一系列for loops 来做到这一点,但我正在寻找更简洁/专业的方法。

谢谢。

【问题讨论】:

  • 请发布您当前的解决方案。此外,代码审查网站更适合解决有关如何改进代码的问题。
  • 提示:看看python的zip()函数。
  • 您不需要一系列循环。看zip() function
  • zip 不会生成字典,但它会组织列表的内容,以使这样做非常简单,无需循环。

标签: python-3.x list dictionary


【解决方案1】:

使用 zip 你至少可以做这个“压缩”的实现:

res = dict()
for n,a,s in zip(names,ages,scores):
   res[n] = [a,s,'fail' if s <60 else 'pass']

【讨论】:

  • 您可以更进一步,完全不需要任何循环。
【解决方案2】:

您可以使用dictionary comprehension 巧妙地做到这一点:

D = {name: [score, age, 'fail' if score<60 else 'pass'] for name, score, age in zip(names, scores, ages)}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-15
    • 1970-01-01
    • 1970-01-01
    • 2015-06-30
    • 1970-01-01
    • 1970-01-01
    • 2018-01-14
    相关资源
    最近更新 更多