a = [1,2,3,4,5,6]
b = [7,7,9,8,8,8]
# 字典 dic_A 合并列表a,b。
dic_A = dict(zip(a,b))
dic_A
{1: 7, 2: 7, 3: 9, 4: 8, 5: 8, 6: 8}
我想 在字典dic_A中 将值相等的键合并,想要的到结果如下
dic_A = {12: 7, 3: 9, 456: 8}
请教一下,应该如何实现呢? 谢谢。
天蓬老师2017-04-18 10:22:47
The questioner didn't make it clear which step to start the conversion from. If you work towards this goal from the beginning of the list, then this problem is actually not difficult.
from itertools import groupby
from functools import reduce
dic_a = {1: 7, 2: 7, 3: 9, 4: 8, 5: 8, 6: 8}
dica = dict([reduce(lambda v, e: (int(str(v[0])+str(e[0])), k), g) for k, g in
groupby(dic_a.items(), lambda v: v[1])])
>>> dica
>>> {3: 9, 12: 7, 456: 8}
ringa_lee2017-04-18 10:22:47
python3
setdefault
>>> a = [1,2,3,4,5,6]
>>> b = [7,7,9,8,8,8]
>>> d={}
>>> for k,v in zip(b,a):
d.setdefault(k,[]).append(v)
>>> d
{8: [4, 5, 6], 9: [3], 7: [1, 2]}
>>>