📜  Python通过匹配元组列表中的第二个元组值进行分组

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

Python通过匹配元组列表中的第二个元组值进行分组

给定一个元组列表,任务是通过匹配元组中的第二个元素来对元组进行分组。我们可以通过检查每个元组中的第二个元素来使用字典来实现这一点。

例子:

Input : [(20, 80), (31, 80), (1, 22), (88, 11), (27, 11)]
Output: {80: [(20, 80), (31, 80)],
         11: [(88, 11), (27, 11)],
         22: [(1, 22)]}

Input : [(20, 'Geek'), (31, 'Geek'), (88, 'NotGeek'), (27, 'NotGeek')]
Output: {'NotGeek': [(88, 'NotGeek'), (27, 'NotGeek')],
         'Geek': [(20, 'Geek'), (31, 'Geek')]}

代码#1:

# Python program to group tuples by matching 
# second tuple value in list of tuples
  
# Initialisation 
Input = [(20, 80), (31, 80), (1, 22), (88, 11), (27, 11)]
  
Output = {}
for x, y in Input:
    if y in Output:
        Output[y].append((x, y))
    else:
        Output[y] = [(x, y)]
  
# Printing Output
print(Output)
输出:
{80: [(20, 80), (31, 80)], 11: [(88, 11), (27, 11)], 22: [(1, 22)]}


代码#2:

# Python program to group tuples by matching 
# second tuple value in list of tuples
  
# Initialisation 
Input = [(20, 'Geek'), (31, 'Geek'), (88, 'NotGeek'), (27, 'NotGeek')]
  
Output = {}
for x, y in Input:
    if y in Output:
        Output[y].append((x, y))
    else:
        Output[y] = [(x, y)]
  
# Printing Output
print(Output)
输出:
{'NotGeek': [(88, 'NotGeek'), (27, 'NotGeek')],
 'Geek': [(20, 'Geek'), (31, 'Geek')]}