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

alw*_*btc 4 python statistics list

我有一份清单清单:

[[1,2], [1,2,4], [1,2,3,4], [4,5,6], [1,9], [1,2,4]]
Run Code Online (Sandbox Code Playgroud)

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

number of lists with 2 elements : 2
number of lists with 3 elements : 3
number of lists with 4 elements : 1
Run Code Online (Sandbox Code Playgroud)

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

mgi*_*son 6

我使用collections.defaultdict:

d = defaultdict(int)
for lst in lists:
   d[len(lst)] += 1
Run Code Online (Sandbox Code Playgroud)

  • @alwbtc - 老实说我通过回答关于SO的问题来学习.有一些类似的问题,通常需要类似的工具来解决它们.过了一会儿,您开始了解哪种工具适合哪种类型的问题.然后你开始回答问题,在你知道之前,你有近15k的声誉:-) (3认同)

djc*_*djc 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)
Run Code Online (Sandbox Code Playgroud)


jam*_*lak 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
Run Code Online (Sandbox Code Playgroud)