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

Counting the amount of occurrences in a list of tuples(计算元组列表中出现的次数)
本文介绍了计算元组列表中出现的次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 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.

这篇关于计算元组列表中出现的次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)