[英]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? 这样做的最好(最pythonic)方式是什么?
I'd use a collections.defaultdict : 我使用collections.defaultdict :
d = defaultdict(int)
for lst in lists:
d[len(lst)] += 1
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)
>>> 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.