📌  相关文章
📜  Python – 元组列表中的第一个元素按第二个元素分组

📅  最后修改于: 2022-05-13 01:55:23.443000             🧑  作者: Mango

Python – 元组列表中的第一个元素按第二个元素分组

给定元组列表,根据第二个元素对第一个元素进行分组。

方法 #1:使用循环 + groupby() + sorted() + 列表理解 + lambda

在这种情况下,元素被排序以进行分组,函数由 lambda 提供,然后使用列表推导从结果中仅提取第一个元素。最后使用循环形成字典。

Python3
# Python3 code to demonstrate working of 
# Group first elements by second elements in Tuple list
# Using loop + groupby() + sorted() + list comprehension + lambda
from itertools import groupby
  
# initializing list
test_list = [(6, 5), (2, 7), (2, 5), (8, 7), (9, 8), (3, 7)]
  
# printing original list
print("The original list is : " + str(test_list))
  
res = dict()
  
# forming equal groups
for key, val in groupby(sorted(test_list, key = lambda ele: ele[1]), key = lambda ele: ele[1]):
    res[key] = [ele[0] for ele in val] 
  
# printing results
print("Grouped Dictionary : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Group first elements by second elements in Tuple list
# Using dictionary comprehension 
from itertools import groupby
  
# initializing list
test_list = [(6, 5), (2, 7), (2, 5), (8, 7), (9, 8), (3, 7)]
  
# printing original list
print("The original list is : " + str(test_list))
  
# shorthand to solve problem
res = {key : [v[0] for v in val] for key, val in groupby(sorted(test_list, key = lambda ele: ele[1]), key = lambda ele: ele[1])}
  
# printing results
print("Grouped Dictionary : " + str(res))


输出
The original list is : [(6, 5), (2, 7), (2, 5), (8, 7), (9, 8), (3, 7)]
Grouped Dictionary : {5: [6, 2], 7: [2, 8, 3], 8: [9]}

方法#2:使用字典理解

这是类似于上面的方法,只是使用字典理解处理的单行速记。

Python3

# Python3 code to demonstrate working of 
# Group first elements by second elements in Tuple list
# Using dictionary comprehension 
from itertools import groupby
  
# initializing list
test_list = [(6, 5), (2, 7), (2, 5), (8, 7), (9, 8), (3, 7)]
  
# printing original list
print("The original list is : " + str(test_list))
  
# shorthand to solve problem
res = {key : [v[0] for v in val] for key, val in groupby(sorted(test_list, key = lambda ele: ele[1]), key = lambda ele: ele[1])}
  
# printing results
print("Grouped Dictionary : " + str(res))
输出
The original list is : [(6, 5), (2, 7), (2, 5), (8, 7), (9, 8), (3, 7)]
Grouped Dictionary : {5: [6, 2], 7: [2, 8, 3], 8: [9]}