我有两个python列表:
keys=[1,2,2,3,2,3]
values=['apple','book','pen','soccer','paper','tennis']
“键”是“值”列表中相应单词的集群ID列表。我希望使用
打印键值对keys=[1,2,2,3,2,3]
values=['apple','book','pen','soccer','paper','tennis']
dictionary = dict(zip(keys, values))
for key, value in dictionary.items() :
print (key, value)
但它只打印
1 apple
2 paper
3 tennis
我真正想要的是获取所有键的所有值,例如
1 [apple]
2 [book,pen,paper]
3 [soccer,tennis]
我知道我的当前代码应该逻辑打印第一个输出,因为键是唯一的。但是如何更改它以便打印所有键的所有值?提前谢谢!
答案 0 :(得分:5)
from collections import defaultdict
keys=[1,2,2,3,2,3]
values=['apple','book','pen','soccer','paper','tennis']
d = defaultdict(list)
for k, v in zip(keys, values):
d[k].append(v)
答案 1 :(得分:3)
看起来你想要的是从一个键到多个值的映射,实现它的一种方法是:
from collections import defaultdict
d = defaultdict(list)
keys=[1,2,2,3,2,3]
values=['apple','book','pen','soccer','paper','tennis']
for tuple in zip(keys, values):
d[tuple[0]].append(tuple[1])
print(d) # defaultdict(<class 'list'>, {1: ['apple'], 2: ['book', 'pen', 'paper'], 3: ['soccer', 'tennis']})
答案 2 :(得分:2)
您可以使用itertools
:
import itertools
keys=[1,2,2,3,2,3]
values=['apple','book','pen','soccer','paper','tennis']
final_data = {a:[i[0] for i in b] for a, b in [(a, list(b)) for a, b in itertools.groupby(sorted(zip(values, keys), key=lambda x:x[-1]), key=lambda x:x[-1])]}
输出:
{1: ['apple'], 2: ['book', 'pen', 'paper'], 3: ['soccer', 'tennis']}
答案 3 :(得分:1)
纯python也有效
keys=[1,2,2,3,2,3]
values=['apple','book','pen','soccer','paper','tennis']
d = dict(zip(keys, [[] for _ in keys])) # dict w keys, empty lists as values
for k, v in zip(keys, values):
d[k].append(v)
d
Out[128]: {1: ['apple'], 2: ['book', 'pen', 'paper'], 3: ['soccer', 'tennis']}
答案 4 :(得分:1)
两种方法:
如果你想要,你可以使用默认的dict,因为已经建议了许多:
数据是:
keys=[1,2,2,3,2,3]
values=['apple','book','pen','soccer','paper','tennis']
方法:1
import collections
d=collections.defaultdict(list)
for i in zip(keys,values):
d[i[0]].append(i[1])
print(d)
输出:
{1: ['apple'], 2: ['book', 'pen', 'paper'], 3: ['soccer', 'tennis']}
或者,如果您想在不导入任何外部模块的情况下开发自己的逻辑,那么您可以尝试:
result={}
for i in zip(keys,values):
if i[0] not in result:
result[i[0]]=[i[1]]
else:
result[i[0]].append(i[1])
print(result)
输出:
{1: ['apple'], 2: ['book', 'pen', 'paper'], 3: ['soccer', 'tennis']}