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

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

什么是最佳(最符合Python风格)的处理方式?
3个回答

6

@delnan,如果您可以使用计数器,那么您就可以这样做! - jamylak
3
@alwbtc -- 老实说,我是通过回答 Stack Overflow 上的问题来学习的。通常有一些相似的问题需要使用类似的工具来解决。一段时间后,你开始学会哪些工具适用于哪种类型的问题。然后你开始回答这些问题,没过多久,你的声望就快达到了 15k :-) - mgilson
@jamylak -- 虽然如果我真的想要向后兼容,我想我可以退而求其次使用dict.setdefault ;^) ... - mgilson
@mgilson 大多数人现在使用的是 >= 2.6 版本。 - jamylak
@jamylak -- 我大部分时间仍在使用2.6版本(主要是因为我太懒了,不想重新安装所有的2.7和3.2实现所需的包)。-- 我甚至有一个备用的odict模块,我的所有脚本都会使用它来导入OrderedDict,如果找不到collections.OrderedDict的话... - mgilson
显示剩余8条评论

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)

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

Counter.most_common() 的意思是返回计数器中出现频率最高的元素。 - mgilson
@mgilson 我正要更改它,但我想我会将其保留为most_common选项。 - jamylak
1
我喜欢它展示了这种用法比我的defaultdict更优越 - 主要是因为Counters有一些很好的方法来处理计数。 - mgilson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接