计算元组列表中出现的次数

2022-01-20 00:00:00 python list tuples counting

问题描述

我对 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 的条目总数.

您仍然可以使用计数器:

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.

相关文章