veingrow veingrow - 1 year ago 79
Python Question

Count sub_lists length in python3

My python is 3 ver.
I have a list, which contains sub lists, like:

L=[[1,2], [3,4], [5,6,7]]


I want to calculate length of all sub_list and write down them to a dictionary, like this:

D={2:2,3:1}


that is, we have 2 lists which have length 2, and 1 list which have the length 3.

It can be done by for-loop + check D[key] is exist or not.

May be there is some 'pythonic way?'

Answer Source

Use defaultdict where you store the length of the list as the key, and just increment each value by 1 every time to get a matching list length:

from collections import defaultdict

d = defaultdict(int)
L = [[1,2], [3,4], [5,6,7]]

for li in L:
    d[len(li)] += 1

print(d) # defaultdict(<class 'int'>, {2: 2, 3: 1})

Or use Counter from collections as well:

from collections import Counter

c = Counter(len(li) for li in L)

print(c) # Counter({2: 2, 3: 1})