Python – 对偶列表矩阵中的元素进行分组
有时,在使用Python列表时,我们可能会遇到一个问题,我们需要将列表中的元素与 Matrix 的第一个元素进行分组,并以字典的形式进行分组。这在许多领域都具有优势。让我们讨论可以执行此任务的某些方式。
方法 #1:使用循环 + 列表推导
上述方法的组合可用于执行此任务。在此,我们遍历对偶元素行并使用列表中的元素映射和对偶行矩阵的第二列计算字典。
# Python3 code to demonstrate
# Group elements from Dual List Matrix
# using loop + list comprehension
# Initializing lists
test_list1 = ['Gfg', 'is', 'best']
test_list2 = [['Gfg', 1], ['is', 2], ['best', 1], ['Gfg', 4], ['is', 8], ['Gfg', 7]]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# Group elements from Dual List Matrix
# using loop + list comprehension
res = {key: [] for key in test_list1}
for key in res:
res[key] = [sub[1] for sub in test_list2 if key == sub[0]]
# printing result
print ("The dictionary after grouping : " + str(res))
The original list 1 is : [‘Gfg’, ‘is’, ‘best’]
The original list 2 is : [[‘Gfg’, 1], [‘is’, 2], [‘best’, 1], [‘Gfg’, 4], [‘is’, 8], [‘Gfg’, 7]]
The dictionary after grouping : {‘is’: [2, 8], ‘Gfg’: [1, 4, 7], ‘best’: [1]}
方法#2:使用字典理解
这是可以执行此任务的另一种方式。在此,我们将上面执行的逻辑编译成一个单一的字典理解,以提高可读性。
# Python3 code to demonstrate
# Group elements from Dual List Matrix
# using dictionary comprehension
# Initializing lists
test_list1 = ['Gfg', 'is', 'best']
test_list2 = [['Gfg', 1], ['is', 2], ['best', 1], ['Gfg', 4], ['is', 8], ['Gfg', 7]]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# Group elements from Dual List Matrix
# using dictionary comprehension
res = {key: [sub[1] for sub in test_list2 if key == sub[0]] for key in test_list1}
# printing result
print ("The dictionary after grouping : " + str(res))
The original list 1 is : [‘Gfg’, ‘is’, ‘best’]
The original list 2 is : [[‘Gfg’, 1], [‘is’, 2], [‘best’, 1], [‘Gfg’, 4], [‘is’, 8], [‘Gfg’, 7]]
The dictionary after grouping : {‘is’: [2, 8], ‘Gfg’: [1, 4, 7], ‘best’: [1]}