请教,关于python字典,合并相同值的键的实现方法
天蓬老师
天蓬老师 2017-04-18 10:20:47
0
3
846
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}

请教一下,应该如何实现呢? 谢谢。

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(3)
Peter_Zhu

Is it okay to look at it this way?

Peter_Zhu

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}
左手右手慢动作

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]}
>>> 
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!