Dada una lista de tuplas, escriba un programa para encontrar el promedio de tuplas similares en la lista.
Ejemplos
Input: [('Geeks', 10), ('For', 10), ('Geeks', 2), ('For', 9), ('Geeks', 10)] Output: Resultant list of tuples: [('For', 9.5), ('Geeks', 7.333333333333333)] Input: [('Akshat', 10), ('Garg', 10), ('Akshat', 2), ('Garg', 9), ('Akshat', 10)] Output: Resultant list of tuples: [('Akshat', 7.333333333333333), ('Garg', 9.5)]
Método n.º 1: usar la comprensión de listas
# Python code to demonstrate # find average of similar tuples in list # initialising list of tuples ini_list = [('Akshat', 10), ('Garg', 10), ('Akshat', 2), ('Garg', 9), ('Akshat', 10)] # finding average of similar entries def avg(l): return sum(l)/len(l) result = [(n, avg([v[1] for v in ini_list if v[0] is n])) for n in set([n[0] for n in ini_list])] # printing result print ("Resultant list of tuples: {}".format(result))
Producción:
Resultant list of tuples: [('Akshat', 7.333333333333333), ('Garg', 9.5)]
Método #2: Convertir en diccionario
# Python code to demonstrate # find average of similar tuples in list # initialising list of tuples ini_list = [('Akshat', 10), ('Garg', 10), ('Akshat', 2), ('Garg', 9), ('Akshat', 10)] # finding average of similar entries temp_dict = dict() for tuple in ini_list: key, val = tuple temp_dict.setdefault(key, []).append(val) result = [] for name, values in temp_dict.items(): result.append((name, (sum(values)/len(values)))) # printing result print("Resultant list of tuples: {}".format(result))
Producción:
Resultant list of tuples: [('Garg', 9.5), ('Akshat', 7.333333333333333)]
Publicación traducida automáticamente
Artículo escrito por manjeet_04 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA