给出两个长度相同的列表:
List1 = ['a','b','c','d','b','a','b','c']
List2 = ['1','2','3','4','5','6','7','8']
我希望输出一个字典:
dic = {'a':['1','6'], 'b':['2','5','7'], 'c':['3','8'], 'd':['4']}
如何在Python中实现它?谢谢!
答案 0 :(得分:4)
您可以使用zip
函数创建(在python 3.X迭代器中)列的列表,并使用dict.setdefault
方法(或collections.defaultdict
)创建一个欲望字典:< / p>
>>> List1 = ['a','b','c','d','b','a','b','c']
>>> List2 = ['1','2','3','4','5','6','7','8']
>>>
>>> d={}
>>> for i,j in zip(List1,List2):
... d.setdefault(i,[]).append(j)
...
>>> d
{'a': ['1', '6'], 'c': ['3', '8'], 'b': ['2', '5', '7'], 'd': ['4']}
如果您关心订单,可以使用collections.OrderedDict
:
>>> from collections import OrderedDict
>>> d=OrderedDict()
>>> for i,j in zip(List1,List2):
... d.setdefault(i,[]).append(j)
...
>>> d
OrderedDict([('a', ['1', '6']), ('b', ['2', '5', '7']), ('c', ['3', '8']), ('d', ['4'])])
>>>
答案 1 :(得分:1)
我会使用collections.defaultdict
和zip()
方法。示例 -
>>> List1 = ['a','b','c','d','b','a','b','c']
>>> List2 = ['1','2','3','4','5','6','7','8']
>>>
>>> from collections import defaultdict
>>> outd = defaultdict(list)
>>> for x,y in zip(List1,List2):
... outd[x].append(y)
...
>>> outd
defaultdict(<class 'list'>, {'c': ['3', '8'], 'd': ['4'], 'b': ['2', '5', '7'], 'a': ['1', '6']})
答案 2 :(得分:0)
使用itertools.groupby
的替代解决方案。实际上,groupby似乎是更自然的解决方案,因为它更倾向于实现它的目标。
总而言之,将两个列表组合在一起,并根据列表中的第一项对它们进行分组。
<强>实施强>
>>> from itertools import groupby
>>> from operator import itemgetter
>>> {k: map(itemgetter(1), v)
for k, v in groupby(sorted(zip(List1, List2)),
key = itemgetter(0))}
<强>输出强>
{'a': ['1', '6'], 'c': ['3', '8'], 'b': ['2', '5', '7'], 'd': ['4']}
正如其他人所提到的那样,如果订单很重要,您可以使用collections.OrderedDict
<强>实施强>
>>> from collections import OrderedDict
>>> OrderedDict((k, map(itemgetter(1), v))
for k, v in groupby(sorted(zip(List1, List2)),
key = itemgetter(0)))
<强>输出强>
OrderedDict([('a', ['1', '6']), ('b', ['2', '5', '7']), ('c', ['3', '8']), ('d', ['4'])])