4

我有一个列表列表:

[[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)方法是什么?

4

3 回答 3

6

我会使用collections.defaultdict

d = defaultdict(int)
for lst in lists:
   d[len(lst)] += 1
于 2012-08-23T14:45:02.257 回答
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)
于 2012-08-23T14:45:10.493 回答
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
于 2012-08-23T14:46:49.277 回答