Home > Enterprise >  Python count and group occurrences of list
Python count and group occurrences of list

Time:11-01

I have the following list in Python:

a = ['426::1898','426::1898','426::1900','425::1898']

And i want my output to be someting like this:

1898: 426 2 times, 425 1 times

1900: 426 1 times

How can i do that?

CodePudding user response:

You can use collections.defaultdict and collections.Counter in a small loop:

from collections import defaultdict, Counter

# computing the counts
counts = defaultdict(Counter)
for v,k in map(lambda s: s.split('::'), a):
    counts[k][v]  = 1
# printing the counts
for k,c in counts.items():
    s = ', '.join(f'{k2} {v2} times' for k2,v2 in c.items())
    print(f'{k}: {s}')

Output:

1898: 426 2 times, 425 1 times
1900: 426 1 times

CodePudding user response:

You can use nested defaultdict (a related post: Nested defaultdict of defaultdict):

from collections import defaultdict

a = ['426::1898','426::1898','426::1900','425::1898']

d = defaultdict(lambda: defaultdict(int))
for value, year in map(lambda u: u.split('::'), a):
    d[year][value]  = 1

for year, subdict in d.items():
    print(year   ':', ', '.join(f"{value} {cnt} times" for value, cnt in subdict.items()))

# 1898: 426 2 times, 425 1 times
# 1900: 426 1 times

(To give somewhat easier-to-understand variable names, I assumed that 1898 and 1990 are years.)

CodePudding user response:

I think it would be pretty easy.

a = ['426::1898','426::1898','426::1900','425::1898']

output = {}
for i in a:
    splitted = i.split("::")
    if splitted[1] in output:
        output[splitted[1]].append(splitted[0])
    else:    
        output[splitted[1]] = [splitted[0]]
print(output)

That's most of the hard bits, feel free to clean it up a bit so it looks like the nice-looking output you show. I may end up editing this answer so it looks like your output.

  • Related