Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get statistic of a list of lists in python?

I have a list of lists:

[[1,2], [1,2,4], [1,2,3,4], [4,5,6], [1,9], [1,2,4]]

I would like to get list statistics in following format:

number of lists with 2 elements : 2
number of lists with 3 elements : 3
number of lists with 4 elements : 1

What is the best (most pythonic) way of doing this?

like image 212
alwbtc Avatar asked Dec 01 '22 21:12

alwbtc


1 Answers

I'd use a collections.defaultdict:

d = defaultdict(int)
for lst in lists:
   d[len(lst)] += 1
like image 173
mgilson Avatar answered Dec 14 '22 16:12

mgilson