如何在python中获得列表列表的统计信息?
我有一份清单:如何在python中获得列表列表的统计信息?,python,list,statistics,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 做这件事最好的方法是什么 @德尔南,若你们可以用计数器代替,你们可以@delnan——是的,这是我的备用设备之一——虽然我
[[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
做这件事最好的方法是什么
@德尔南,若你们可以用计数器代替,你们可以@delnan——是的,这是我的备用设备之一——虽然我也想更习惯于使用
计数器
。@jamylak Counter很不错,但不是更方便,更专业。我目前的代码库对defaultdict
有十几个很好的用途,但在Counter
更适合的地方没有一个。我试着去适应它,但我很少去使用它。@mgilson太好了,你是怎么学会的?你研究过所有的python模块吗?还是你通过问别人来学习?@alwbtc——老实说,我是通过回答这样的问题来学习的。有一系列类似的问题,通常需要类似的工具来解决。一段时间后,您开始了解哪些工具适合于哪种类型的问题。然后你开始回答问题,不知不觉中,你已经拥有了将近15k的声誉:-)(+1)对于Counter.most_common()
@mgilson我正要更改它,但我想我会把它留给最常见的选项。我喜欢这一点,它表明了这种用法如何优于我的defaultdict
——主要是计数器的方法非常适合处理计数。
d = defaultdict(int)
for lst in lists:
d[len(lst)] += 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