2 回答
TA贡献1155条经验 获得超0个赞
使用defaultdictwithlist工厂作为输出容器,并使用以下命令遍历两个列表zip:
In [162]: out = collections.defaultdict(list)
In [163]: for k, v in zip(fruits, val):
...: out[k].append(v)
...:
In [164]: out
Out[164]:
defaultdict(list,
{'apple': ['a', 'b', 'e'], 'oranges': ['c'], 'watermelon': ['d']})
In [165]: dict(out)
Out[165]: {'apple': ['a', 'b', 'e'], 'oranges': ['c'], 'watermelon': ['d']}
TA贡献1906条经验 获得超10个赞
您可以使用setdefault一个空列表初始化每个值,然后附加另一个列表中的值
fruits = ["apple","apple","oranges","watermelon","apple"]
val = ["a","b","c","d","e"]
d={}
for k, v in zip(fruits, val):
d.setdefault(k, []).append(v)
print(d)
# {'apple': ['a', 'b', 'e'], 'oranges': ['c'], 'watermelon': ['d']}
添加回答
举报