Assegnare un Valore a una lista in python e somma i valori

0

Domanda

questo è un esercizio in python, non so usare panda appena built-in funzioni python. Ho questa lista:

 ['a', 1],
 ['b', 1],
 ['a', 2],
 ['a', 2],

L'output dovrebbe essere simile:

 ['a', 5],
 ['b', 1],

Questo è il codice che ho finora, ma io sto fondamentalmente stesso elenco.

result = []

for x,y in list_data:
    if x not in result: 
        result.append([x, int(y)])
    else:
        result[1] += int(y) 
result
built-in function list python
2021-11-24 02:37:03
4

Migliore risposta

1

Si può fare un dizionario per calcolare i totali e poi riconvertirlo in un elenco:

data = [['c', 2], ['a', 1], ['b', 1], ['a', 2], ['a', 2], ['c', 3]]

totals = {} # could use collections.defaultdict for this part
for k, v in data:
    totals[k] = totals.get(k, 0) + v
print(totals) # {'c': 5, 'a': 5, 'b': 1}
output = [[k, v] for k, v in totals.items()]
# or, output = list(map(list, totals.items()))
# or, output = list(totals.items()) # if you are fine with a list of tuples
print(output) # [['c', 5], ['a', 5], ['b', 1]]

# if you want the output to be sorted alphabetically
output = sorted(output, key=lambda lst: lst[0])
print(output) # [['a', 5], ['b', 1], ['c', 5]]
2021-11-24 02:50:31

Funziona, si può suggerire di me come ordinare gli elementi in ordine alfabetico
Luis Alejandro Vargas Ramos

@LuisAlejandroVargasRamos non è già ordinati?
j1-lee

@LuisAlejandroVargasRamos Grande, ho aggiunto l'ordinamento parte alla fine del codice, con nuovi elementi che coinvolgono c in ingresso.
j1-lee
1

One-liner:

import itertools

[[x[0], sum([value[1] for value in x[1]])] for x in itertools.groupby(sorted(list_data), lambda i: i[0])]

Dettagli:

[[x[0], sum([value[1] for value in x[1]])] for x in itertools.groupby(sorted(list_data), lambda i: i[0])]
                                                                      sorted(list_data)                    # sort the list alphabetically
                                                    itertools.groupby(sorted(list_data), lambda i: i[0])   # group by the "key"
                                                                                                           # result: [('a', <itertools._grouper object at 0x000001D6B806F700>), ('b', <itertools._grouper object at 0x000001D6B806F310>)]
  x[0]                                     for x in                                                        # ['a', 'b']
            [value[1] for value in x[1]]   for x in                                                        # [[1, 2, 2], [1]]
        sum([value[1] for value in x[1]])  for x in                                                        # [5, 1]
  x[0], sum([value[1] for value in x[1]])  for x in                                                        # [['a', 5], ['b', 1]]
2021-11-24 02:43:18
0

Il dizionario è la migliore pratica per il vostro compito.

data = [['a', 1], ['b', 1], ['a', 2], ['a', 2]]
d = {}
for key, value in data:
    d[key] = value + (d[key] if key in d else 0)
# generate list of tuples and sort
out = sorted(d.items())
print(out)
2021-11-24 02:50:46
0

Sembra che si sta pensando di liste, come un dizionario. Per il codice per funzionare è necessario trovare il risultato dell'indice che si desidera aggiungere il valore (risultato[1]).

Ma se si modifica il risultato di un dizionario si può tenere quasi lo stesso codice:

result = dict() # or result = {}
for x,y in list_data:
    if x not in result: 
        result[x] = int(y)
    else:
        result[x] += y

print(result)

Out[1]: {'a': 5, 'b': 1}

Se si desidera disporre di un elenco, è possibile utilizzare:

result_list = []
for x,y in result.items():
    result_list.append([x,y])
    
print(result_list)
[['a', 5], ['b', 1]]
2021-11-24 02:56:01

In altre lingue

Questa pagina è in altre lingue

Русский
..................................................................................................................
Polski
..................................................................................................................
Română
..................................................................................................................
한국어
..................................................................................................................
हिन्दी
..................................................................................................................
Français
..................................................................................................................
Türk
..................................................................................................................
Česk
..................................................................................................................
Português
..................................................................................................................
ไทย
..................................................................................................................
中文
..................................................................................................................
Español
..................................................................................................................
Slovenský
..................................................................................................................