Python|合并键值列表
有时,在使用列表时,我们可能会遇到一个问题,即我们需要执行合并函数,其中我们拥有键列表,并且需要在其他列表中创建具有相应值的字典映射键。让我们讨论可以执行此任务的某些方式。
方法 #1:使用zip()
+ loop + defaultdict()
上述方法的组合可用于执行此特定任务。在这种情况下,我们使用 zip函数将列表中的相似元素相互匹配,然后使用循环将值分配给压缩列表中的键,以将值添加到 defaultdict。
# Python3 code to demonstrate working of
# Merge key value list
# Using zip() + loop + defaultdict()
from collections import defaultdict
# initializing lists
test_list1 = [0, 0, 0, 1, 1, 1, 2, 2]
test_list2 = ['gfg', 'is', 'best', 'Akash', 'Akshat', 'Nikhil', 'apple', 'grapes']
# printing original lists
print("The original list1 is : " + str(test_list1))
print("The original list2 is : " + str(test_list2))
# Using zip() + loop + defaultdict()
# Merge key value list
res = defaultdict(list)
for i, j in zip(test_list1, test_list2):
res[i].append(j)
# printing result
print("The merged key value dictionary is : " + str(dict(res)))
The original list1 is : [0, 0, 0, 1, 1, 1, 2, 2]
The original list2 is : [‘gfg’, ‘is’, ‘best’, ‘Akash’, ‘Akshat’, ‘Nikhil’, ‘apple’, ‘grapes’]
The merged key value dictionary is : {0: [‘gfg’, ‘is’, ‘best’], 1: [‘Akash’, ‘Akshat’, ‘Nikhil’], 2: [‘apple’, ‘grapes’]}
方法 #2:使用itemgetter() + groupby() + zip()
这是执行此特定任务的另一种方式。在此,我们将itemgetter
获取的键与其他列表的元素分组到第一个列表,该列表使用zip
函数使用groupby
方法链接。
# Python3 code to demonstrate working of
# Merge key value list
# Using itemgetter() + groupby() + zip()
from itertools import groupby
from operator import itemgetter
# initializing lists
test_list1 = [0, 0, 0, 1, 1, 1, 2, 2]
test_list2 = ['gfg', 'is', 'best', 'Akash', 'Akshat', 'Nikhil', 'apple', 'grapes']
# printing original lists
print("The original list1 is : " + str(test_list1))
print("The original list2 is : " + str(test_list2))
# Using itemgetter() + groupby() + zip()
# Merge key value list
res = {keys: [i for _, i in sub] for keys, sub in groupby(
zip(test_list1, test_list2), key = itemgetter(0))}
# printing result
print("The merged key value dictionary is : " + str(dict(res)))
The original list1 is : [0, 0, 0, 1, 1, 1, 2, 2]
The original list2 is : [‘gfg’, ‘is’, ‘best’, ‘Akash’, ‘Akshat’, ‘Nikhil’, ‘apple’, ‘grapes’]
The merged key value dictionary is : {0: [‘gfg’, ‘is’, ‘best’], 1: [‘Akash’, ‘Akshat’, ‘Nikhil’], 2: [‘apple’, ‘grapes’]}