如何将多个列表映射到一本词典? [英] How to map multiple lists to one dictionary?
问题描述
我使用了以下代码:
dictionary = dict(zip(list1, list2))
以便在字典中映射两个列表.其中:
in order to map two lists in a dictionary. Where:
list1 = ('a','b','c')
list2 = ('1','2','3')
字典等于:
{'a': 1, 'c': 3, 'b': 2}
是否可以添加第三个列表:
Is there a way to add a third list:
list3 = ('4','5','6')
以便字典等于:
{'a': [1,4], 'c': [3,5], 'b': [2,6]}
必须添加第三个列表,以使其遵循现有映射.
This third list has to be added so that it follows the existing mapping.
这个想法是让它在for循环中迭代地完成这项工作,并为正确映射的关键字提供数十个值. 这样可能吗?
The idea is to make this work iteratively in a for loop and several dozens of values to the correctly mapped keyword. Is something like this possible?
希望我的问题很清楚.
推荐答案
dict((z[0],list(z[1:])) for z in zip(list1,list2,list3))
将起作用.或者,如果您更喜欢python2.7 +的更好的dict-comprehension语法,则
will work. Or, if you prefer the slightly nicer dict-comprehension syntax of python2.7+
{z[0]:list(z[1:]) for z in zip(list1,list2,list3)}
这可以轻松扩展到任意数量的列表:
This scales up to to an arbitrary number of lists easily:
list_of_lists = [list1,list2,list3,...]
{z[0]:list(z[1:]) for z in zip(*list_of_lists)}
如果要转换类型以确保值列表包含所有整数:
And if you want to convert the type to make sure that the value lists contain all integers:
def to_int(iterable):
return [int(x) for x in iterable]
{z[0]:to_int(z[1:]) for z in zip(*list_of_lists)}
当然,您可以在1行中完成此操作,但我宁愿不这样做.
Of course, you could do that in 1 line, but I'd rather not.
这篇关于如何将多个列表映射到一本词典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!