我该如何从这样的列表中创建一个字典:
list = [('a', [10,3]), ('a', [30,20]), ('b', [96,45]), ('b', [4,20])]
我想要的结果是:
dict = { 'a':[10,3,30,20], 'b':[96,45,4,20] }
我该如何从这样的列表中创建一个字典:
list = [('a', [10,3]), ('a', [30,20]), ('b', [96,45]), ('b', [4,20])]
dict = { 'a':[10,3,30,20], 'b':[96,45,4,20] }
collections.defaultdict
来实现此功能:>>> from collections import defaultdict
>>> lst = [('a', [10,3]), ('a', [30,20]), ('b', [96,45]), ('b', [4,20])]
>>> dct = defaultdict(list)
>>> for x, y in lst:
... dct[x] += y
...
>>> dct
defaultdict(<class 'list'>, {'a': [10, 3, 30, 20], 'b': [96, 45, 4, 20]})
>>>
或者,如果你想避免导入,可以尝试使用dict.setdefault
:
>>> lst = [('a', [10,3]), ('a', [30,20]), ('b', [96,45]), ('b', [4,20])]
>>> dct = {}
>>> for x, y in lst:
... dct.setdefault(x, []).extend(y)
...
>>> dct
{'a': [10, 3, 30, 20], 'b': [96, 45, 4, 20]}
>>>
sortedi(items)
即可)from itertools import groupby
from operator import itemgetter
items = [('a', [10,3]), ('a', [30,20]), ('b', [96,45]), ('b', [4,20])]
d = dict((key, sum((list_ for _key, list_ in group), []))
# for each group create a key, value tuple. with the value being the
# concatenation of all the lists in the group. eg. [10, 3] + [30, 20]
for key, group in groupby(items, itemgetter(0)))
# group elements in items by the first item in each element
defaultdict
并不完全像dict
- 所以在使用之前,您可能希望将其转换为dict()
。 - Ben