Dada una lista de tuplas, la tarea es agrupar las tuplas haciendo coincidir el segundo elemento de las tuplas. Podemos lograr esto usando el diccionario al verificar el segundo elemento en cada tupla.
Ejemplos:
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')]}
Código #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)
Producción:
{80: [(20, 80), (31, 80)], 11: [(88, 11), (27, 11)], 22: [(1, 22)]}
Código #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)
Producción:
{'NotGeek': [(88, 'NotGeek'), (27, 'NotGeek')], 'Geek': [(20, 'Geek'), (31, 'Geek')]}
Publicación traducida automáticamente
Artículo escrito por everythingispossible y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA