Home > Mobile >  how count the second elements of a nested list where they have the first elements identical?
how count the second elements of a nested list where they have the first elements identical?

Time:05-10

I have a nested list like below:

[['A',4],['U',9],['O',9],['A',1],['O',2],['O',1]]

How I can count the second elements if they have the same first element?

output:

A,5
U,9
O,12 

without using non-efficient for loops

CodePudding user response:

Use a Counter.

from collections import Counter

L = [['A', 4], ['U', 9], ['O', 9], ['A', 1], ['O', 2], ['O', 1]]

c = Counter()
for item, count in L:
    c[item]  = count
>>> c
Counter({'O': 12, 'U': 9, 'A': 5})

If insertion order is important, note that Counter shows its items in sorted descending order, but if you iterate through it, insertion order is preserved:

>>> list(c)
['A', 'U', 'O']

CodePudding user response:

One of the options is to use defaultdict with int as default. For int default value is 0.

from collections import defaultdict

l = [["A", 4], ["U", 9], ["O", 9], ["A", 1], ["O", 2], ["O", 1]]

d = defaultdict(int)

for i in l:
    k, v = i
    d[k]  = v
    
# defaultdict(<class 'int'>, {'A': 5, 'U': 9, 'O': 12})

print("\n".join(f"{k},{v}" for k, v in d.items()))
# A,5
# U,9
# O,12

CodePudding user response:

This should work :

l = [['A', 4], ['U', 9], ['O', 9], ['A', 1], ['O', 2], ['O', 1]]
d = dict()
for i in l : 
    if not (i[0] in d.keys()) :
        d[i[0]] = i[1]
    else :
        d[i[0]]  = i[1]
  • Related