从两个可迭代对象创建字典并使用它们
假设我有两个列表,我想用它们制作一本字典。就像:
>>> l = [1, 2, 3, 4, 5]
>>> x = ['a', 'b', 'c']
>>> dict(zip(l, x))
{1: 'a', 2: 'b', 3: 'c'}
这正如我希望的那样工作,并且由于列表的长度不相等,因此元素 4
和 5
被遗漏,并且没有相应的值他们。这正如预期的那样。
但是,如果我想要一个值,例如 l
中的键为 None
,该怎么办?我希望输出为:
{1: 'a', 2: 'b', 3: 'c', 4: None, 5: None}
我认为的解决方案之一是要迭代两者,请比较它们的长度并在需要时附加 None
。我有一个也有效的解决方案,但我想知道它是否可以以更简单和更短的方式完成?
Suppose I have two lists and I want to make a dictionary from them. Like:
>>> l = [1, 2, 3, 4, 5]
>>> x = ['a', 'b', 'c']
>>> dict(zip(l, x))
{1: 'a', 2: 'b', 3: 'c'}
This works as I'd want it to and since the lists are not of equal length, the elements 4
and 5
are left out and there is no corresponding value for them. That is as expected.
But what if I want a value, say None
for the keys in l
? I'd want the output to be:
{1: 'a', 2: 'b', 3: 'c', 4: None, 5: None}
One of the solutions I thought was to iterate over both, compare their lengths and append None
where required. I have a solution that works also, but I was wondering whether it can be done in a much easier and shorter way perhaps?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用
Use