我有一个类似的数组:
[['foo', 9283], ['bar', 7172], ['bar', 9890], ['foo', 2291], ['fuubar', 8291]]我希望在list[i][0]中计数相同的值,而不指定要查找的字符串。我在互联网上找到的例子要么是关于一维数组的,要么是带有规范的。如果我有一个一维数组,那将非常简单:
示例1,指定值(1)
[1, 2, 3, 4, 1, 4, 1].count(1)
3示例2,但没有具体说明要查找什么
>>> from collections import Counter
>>> z = ['blue', 'red', 'blue', 'yellow', 'blue', 'red']
>>> Counter(z)
Counter({'blue': 3, 'red': 2, 'yellow': 1})我想要的输出也是类似的。举我的例子,我想知道“foo”、“bar”、“fuubar”发生了多少次。但是如何用二维数组来实现呢?
发布于 2015-02-16 13:37:29
使用生成器表达式提取要计数的项:
>>> from collections import Counter
>>> l = [['foo', 9283], ['bar', 7172], ['bar', 9890], ['foo', 91], ['fuubar', 8291]]
>>> Counter(item[0] for item in l)
Counter({'foo': 2, 'bar': 2, 'fuubar': 1})发布于 2015-02-16 13:37:06
Counter([z[0] for z in [['foo', 9283], ['bar', 7172], ['bar', 9890], ['foo', 91], ['fuubar', 8291]]])发布于 2015-02-16 13:46:06
你可以拆开:
Counter(s for s, _ in l))或功能方法:
from operator import itemgetter
print(Counter(map(itemgetter(0), l)))https://stackoverflow.com/questions/28542642
复制相似问题