【发布时间】:2021-02-17 17:08:46
【问题描述】:
A=[1,2,3,4,5]
B=['a','b','c']
我想要输出:
{1: 'a', 2: 'b', 3: 'c', 4: None, 5: None}
我们可以有任意数量的键。
我想在 python 中使用字典理解创建一个包含这两个列表的字典,列表 A 将成为键,其他是键 4 和 5 的值,我们必须打印 None 和其他具有相应值的键我们如何使用听写理解。 提前致谢。
【问题讨论】:
-
你有没有尝试过什么?
-
将 zip_longest 与字典理解一起使用。
-
无论如何,只要使用
itertools.zip_longest:dict(zip_longest(B, A))不需要字典理解 -
{a:b for a,b in itertools.zip_longest(A,B)} -
通常,一个好的答案是“你应该这样做 this 方式”
标签: python dictionary-comprehension