我有一个列表的列表:
[[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风格)的处理方式?
我有一个列表的列表:
[[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
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
Counter.most_common()
的意思是返回计数器中出现频率最高的元素。 - mgilsondefaultdict
更优越 - 主要是因为Counters
有一些很好的方法来处理计数。 - mgilson
dict.setdefault
;^) ... - mgilsonodict
模块,我的所有脚本都会使用它来导入OrderedDict
,如果找不到collections.OrderedDict
的话... - mgilson