在Python中组合列表字典
我有一个非常大的(p,q)元组集合,我想将其转换为列表字典,其中每个元组中的第一项是索引包含q的列表的键 例如:在Python中组合列表字典,python,list,dictionary,Python,List,Dictionary,我有一个非常大的(p,q)元组集合,我想将其转换为列表字典,其中每个元组中的第一项是索引包含q的列表的键 例如: Original List: (1, 2), (1, 3), (2, 3) Resultant Dictionary: {1:[2, 3], 2:[3]} Original Dictionaries: {1:[2, 3], 2:[3]}, {1:[4], 3:[1]} Resultant Dictionary: {1:[2, 3, 4], 2:[3], 3:[1]}
Original List: (1, 2), (1, 3), (2, 3)
Resultant Dictionary: {1:[2, 3], 2:[3]}
Original Dictionaries: {1:[2, 3], 2:[3]}, {1:[4], 3:[1]}
Resultant Dictionary: {1:[2, 3, 4], 2:[3], 3:[1]}
此外,我想有效地结合这些词典
例如:
Original List: (1, 2), (1, 3), (2, 3)
Resultant Dictionary: {1:[2, 3], 2:[3]}
Original Dictionaries: {1:[2, 3], 2:[3]}, {1:[4], 3:[1]}
Resultant Dictionary: {1:[2, 3, 4], 2:[3], 3:[1]}
这些操作驻留在一个内部循环中,因此我希望它们尽可能快
提前感谢德伐迪克特(一如既往)对救援行动的帮助
可以这样组合两个DICT(请注意,将保留重复项):
工作原理如下:
from collections import defaultdict
dic = defaultdict(list)
for i, j in tuples:
dic[i].append(j)
与此类似的是:
a, b = {1:[2, 3], 2:[3]}, {1:[4], 3:[1]}
de = defaultdict(list, a)
for i, j in b.items():
de[i].extend(j)
这里是迭代器的风格 >>> mylist=[(1, 2), (1, 3), (2, 3)] >>> from itertools import groupby >>> from operator import itemgetter >>> mylist=[(1, 2), (1, 3), (2, 3)] >>> groupby(mylist,itemgetter(0)) >>> list(_) [(1, <itertools._grouper object at 0xb7d402ec>), (2, <itertools._grouper object at 0xb7c716ec>)] >>>mylist=[(1,2)、(1,3)、(2,3)] >>>从itertools导入groupby >>>从运算符导入itemgetter >>>mylist=[(1,2)、(1,3)、(2,3)] >>>groupby(mylist,itemgetter(0)) >>>名单 [(1, ), (2, )]
如果元组列表已排序,@gnibler建议的
itertools.groupby
,不是defaultdict
的坏选择,但它的使用需要与他建议的不同:
import itertools
import operator
def lot_to_dict(lot):
key = operator.itemgetter(0)
# if lot's not sorted, you also need...:
# lot = sorted(lot, key=key)
# NOT in-place lot.sort to avoid changing it!
grob = itertools.groupby(lot, key)
return dict((k, [v[1] for v in itr]) for k, itr in grob)
对于将清单目录“合并”为新的d.o.l.:
def merge_dols(dol1, dol2):
keys = set(dol1).union(dol2)
no = []
return dict((k, dol1.get(k, no) + dol2.get(k, no)) for k in keys)
我给[]
起了一个昵称no
,以避免无用地构建大量空列表,因为性能很重要。如果DOL的两组密钥仅略微重叠,则速度会更快:
def merge_dols(dol1, dol2):
result = dict(dol1, **dol2)
result.update((k, dol1[k] + dol2[k])
for k in set(dol1).intersection(dol2))
return result
因为这只对重叠的键使用列表链接——所以,如果这些键很少,它会更快。我希望这些键在一行中完成,只是为了好玩:
>>> from itertools import groupby
>>> t=(1, 2), (1, 3), (2, 3)
>>> [(i,[x for _,x in list(f)]) for i,f in groupby(sorted(t),lambda t: t[0])]
[(1, [2, 3]), (2, [3])]
>>> b={1:[2, 3], 2:[3]}, {1:[4], 3:[1]}
>>> dict([(key,sum([i[1::][0] for i in elements],[])) for key,elements in groupby(sorted(b[0].items()+b[1].items()),lambda t: t[0])])
{1: [2, 3, 4], 2: [3], 3: [1]}
我想你需要。从元组中追加()项。你的第二个循环不可操作这不是OP要求的,是吗?2016和
merge_dols
v.1听起来很棒,谢谢!v、 但是,2使用:dict(dol1,**dol2)