Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

219
Views
python: suma valores en una lista si comparten la primera palabra

Tengo una lista de la siguiente manera,

 flat_list = ['hello,5', 'mellow,4', 'mellow,2', 'yellow,2', 'yellow,7', 'hello,7', 'mellow,7', 'hello,7']

Me gustaría obtener la suma de los valores si comparten la misma palabra, por lo que el resultado debería ser,

salida deseada:

 l = [('hello',19), ('yellow', 9), ('mellow',13)]

hasta ahora, he intentado lo siguiente,

 new_list = [v.split(',') for v in flat_list] d = {} for key, value in new_list: if key not in d.keys(): d[key] = [key] d[key].append(value) # getting rid of the first key in value lists val = [val.pop(0) for k,val in d.items()] # summing up the values va = [sum([int(x) for x in va]) for ka,va in d.items()]

sin embargo, por alguna razón, el último resumen no funciona y no obtengo el resultado deseado

over 4 years ago · Santiago Trujillo
5 answers
Answer question

0

Aquí hay una variante para lograr su objetivo usando defaultdict :

 from collections import defaultdict t = ['hello,5', 'mellow,4', 'mellow,2', 'yellow,2', 'yellow,7', 'hello,7', 'mellow,7', 'hello,7'] count = defaultdict(int) for name_number in t: name, number = name_number.split(",") count[name] += int(number)

También puedes usar Counter :

 from collections import Counter count = Counter() for name_number in t: name, number = name_number.split(",") count[name] += int(number)

En ambos casos, puede convertir la salida en una list de tuple usando:

 list(count.items()) # -> [('hello', 19), ('mellow', 13), ('yellow', 9)]

Ejecuté su código y obtuve los resultados correctos (aunque no en el formato deseado).

over 4 years ago · Santiago Trujillo Report

0

Un posible enfoque sería:

 import pandas as pd flat_list = ['hello,5', 'mellow,4', 'mellow,2', 'yellow,2', 'yellow,7', 'hello,7', 'mellow,7', 'hello,7'] new_list = [v.split(',') for v in flat_list] df = pd.DataFrame(new_list) df[1] = df[1].astype(int) df2 = df.groupby(0).sum() print(df2)

Producción:

 0 1 hello 19 mellow 13 yellow 9
over 4 years ago · Santiago Trujillo Report

0

Puede hacer esto de manera muy simple sin importar módulos adicionales como este:

 t = ['hello,5', 'mellow,4', 'mellow,2', 'yellow,2', 'yellow,7', 'hello,7', 'mellow,7', 'hello,7'] d = {} for s in t: #for each string w, n = s.split(',') #get the string and the number d[w] = d[w] + int(n) if w in d.keys() else int(n) #add the number (sum) l = list(d.items()) #make the result a list of tuples print(l)

Producción:

 [('hello', 19), ('mellow', 13), ('yellow', 9)]
over 4 years ago · Santiago Trujillo Report

0

por alguna razon el ultimo resumen no funciona

Para arreglar su solución original:

 d = {ka:sum([int(x) for x in va]) for ka,va in d.items()}
over 4 years ago · Santiago Trujillo Report

0

el último resumen no funciona y no obtengo el resultado deseado

En realidad, funciona bien, simplemente se olvidó de combinar las dos listas. Agregar

 print(list(zip(val, va)))

y verás:

 [('hello', 19), ('mellow', 13), ('yellow', 9)]

Eso es equivalente a la salida deseada:

 [('hello',19), ('yellow', 9), ('mellow',13)]

Solo las entradas para yellow y mellow están en orden diferente, ya que mellow aparece primero en la entrada.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!