Reputation: 29495
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?
Upvotes: 4
Views: 2727
Reputation: 133694
>>> from collections import Counter
>>> seq = [[1,2], [1,2,4], [1,2,3,4], [4,5,6], [1,9], [1,2,4]]
>>> for k, v in Counter(map(len, seq)).most_common():
print 'number of lists with {0} elements: {1}'.format(k, v)
number of lists with 3 elements: 3
number of lists with 2 elements: 2
number of lists with 4 elements: 1
Upvotes: 6
Reputation: 11731
for k, v in sorted(collections.Counter(len(i) for i in list_of_lists).iteritems()):
print 'number of lists with %s elements : %s' % (k, v)
Upvotes: 6
Reputation: 310137
I'd use a collections.defaultdict:
d = defaultdict(int)
for lst in lists:
d[len(lst)] += 1
Upvotes: 6