计算元组列表中的出现次数
我对python还是很陌生,但是我无法在任何地方找到解决我问题的方法.
I am fairly new to python, but I haven't been able to find a solution to my problem anywhere.
我想计算一个元组列表中一个字符串的出现次数.
I want to count the occurrences of a string inside a list of tuples.
这是元组列表:
list1 = [
('12392', 'some string', 'some other string'),
('12392', 'some new string', 'some other string'),
('7862', None, 'some other string')
]
我已经尝试过了,但是它只能打印0
I've tried this but it just prints 0
for entry in list1:
print list1.count(entry[0])
由于同一ID在列表中出现两次,因此应返回:
As the same ID occurs twice in the list, this should return:
2
1
我还尝试为每次出现相同ID的计数器增加一个计数器,但不太了解如何编写.
I also tried to increment a counter for each occurrence of the same ID but couldn't quite grasp how to write it.
*使用Eumiro的出色答案.我只是意识到我没有解释整个问题.我实际上需要值大于1的条目总数.但是,如果我尝试这样做:
* Using Eumiro's awesome answer. I just realized that I didn't explain the whole problem. I actually need the total amount of entries which has a value more than 1. But if I try doing:
for name, value in list1:
if value > 1:
print value
我收到此错误:
ValueError: Too many values to unpack
也许 collections.Counter
可以解决您的问题:
Maybe collections.Counter
could solve your problem:
from collections import Counter
Counter(elem[0] for elem in list1)
返回
Counter({'12392': 2, '7862': 1})
速度很快,因为它仅对列表进行一次迭代.您遍历条目,然后尝试获取列表中这些条目的数量.不能使用 .count
完成此操作,但可以按以下步骤完成:
It is fast since it iterates over your list just once. You iterate over entries and then try to get a count of these entries within your list. That cannot be done with .count
, but might be done as follows:
for entry in list1:
print sum(1 for elem in list1 if elem[0] == entry[0])
但是认真的看一下 collections.Counter
.
编辑:我实际上需要值大于1的条目总数.
您仍然可以使用 Counter
:
c = Counter(elem[0] for elem in list1)
sum(v for k, v in c.iteritems() if v > 1)
返回 2
,即大于1的计数之和.
returns 2
, i.e. the sum of counts that are higher than 1.