如何在python中获取列表列表的统计信息?

时间:2012-08-23 14:43:01

标签: python list statistics

我有一份清单清单:

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

我想以下列格式获取列表统计信息:

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

最好的(最pythonic)方式是什么?

3 个答案:

答案 0 :(得分:6)

我使用collections.defaultdict

d = defaultdict(int)
for lst in lists:
   d[len(lst)] += 1

答案 1 :(得分:6)

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)

答案 2 :(得分:6)

>>> 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
相关问题