list1 = [123, 123, 123, 456]
list2 = ['word1', 'word2', 'word3', 'word4']
我希望输出为python字典,
d = {123 : ['word1', 'word2', 'word3'], 456 : 'word4'}
我在列表1中多次出现值,我想将list2的所有值映射到list1而不重复键。
import collections
list1 = [123, 123, 123, 456]
list2 = ['word1', 'word2', 'word3', 'word4']
dict_value = collections.defaultdict(list)
for key, value in zip(list1, list2):
dict_value[key].append(value)
for i in dict_value:
print('key', i, 'items', dict_value[i], sep = '\t')
输出:
key 123 items ['word1', 'word2', 'word3'] key 456 items ['word4']
itertools
的方法:from itertools import groupby, islice
list1 = [123, 123, 123, 456]
list2 = iter(['word1', 'word2', 'word3', 'word4'])
{k:list(islice(list2, len(list(v)))) for k,v in groupby(list1)}
# {123: ['word1', 'word2', 'word3'], 456: ['word4']}