如果我有2个列表:
fruits = ["apple","apple","oranges","watermelon","apple"]
val = ["a","b","c","d","e"]
val的每个索引对应于水果的索引
因此,如果我要使用以下字典:
dict
{
"apple" : ["a","b","e"],
"oranges": ["c"],
"watermelon": ["d"]
}
最简单的方法是什么?
答案 0 :(得分:4)
使用带有defaultdict
工厂的list
作为输出容器,并使用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']}
答案 1 :(得分:0)
您可以使用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']}