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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16013485/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 21:35:35  来源:igfitidea点击:

Counting the amount of occurrences in a list of tuples

pythonlisttuplescounting

提问by mackwerk

I am fairly new to python, but I haven't been able to find a solution to my problem anywhere.

我对python相当陌生,但我无法在任何地方找到解决我的问题的方法。

I want to count the occurrences of a string inside a list of tuples.

我想计算一个字符串在元组列表中的出现次数。

Here is the list of tuples:

这是元组列表:

list1 = [
         ('12392', 'some string', 'some other string'),
         ('12392', 'some new string', 'some other string'),
         ('7862', None, 'some other string')
        ]

I've tried this but it just prints 0

我试过这个,但它只打印 0

for entry in list1:
    print list1.count(entry[0])

As the same ID occurs twice in the list, this should return:

由于相同的 ID 在列表中出现两次,这应该返回:

2
1

I also tried to increment a counter for each occurrence of the same ID but couldn't quite grasp how to write it.

我还尝试为每次出现相同的 ID 增加一个计数器,但无法完全掌握如何编写它。

*EDIT: 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:

*编辑:使用 Eumiro 的精彩答案。我才意识到我没有解释整个问题。我实际上需要值大于 1 的条目总数。但是如果我尝试这样做:

for name, value in list1:

    if value > 1:
        print value

I get this error:

我收到此错误:

ValueError: Too many values to unpack

采纳答案by eumiro

Maybe collections.Countercould solve your problem:

也许collections.Counter可以解决您的问题:

from collections import Counter
Counter(elem[0] for elem in list1)

returns

返回

Counter({'12392': 2, '7862': 1})

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:

它很快,因为它只迭代你的列表一次。您遍历条目,然后尝试获取列表中这些条目的计数。这不能用 完成.count,但可以按如下方式完成:

for entry in list1:
    print sum(1 for elem in list1 if elem[0] == entry[0])

But seriously, have a look at collections.Counter.

但说真的,看看collections.Counter

EDIT: I actually need the total amount of entries which has a value more than 1.

编辑我实际上需要值大于 1 的条目总数。

You can still use the Counter:

您仍然可以使用Counter

c = Counter(elem[0] for elem in list1)
sum(v for k, v in c.iteritems() if v > 1)

returns 2, i.e. the sum of counts that are higher than 1.

返回2,即大于 1 的计数总和。

回答by jamylak

list1.count(entry[0])will not work because it looks at each of the three tuples in list1, eg. ('12392', 'some string', 'some other string')and checks if they are equal to '12392'for example, which is obviously not the case.

list1.count(entry[0])将不起作用,因为它会查看 中的三个元组中的每一个list1,例如。('12392', 'some string', 'some other string')并检查它们是否等于'12392'例如,这显然不是这种情况。

@eurmiro's answer shows you how to do it with Counter(which is the best way!) but here is a poor man's version to illustrate how Counterworks using a dictionary and the dict.get(k, [,d])method which will attempt to get a key (k), but if it doesn't exist it returns the default value instead (d):

@eurmiro 的回答向您展示了如何使用Counter(这是最好的方法!)但这里有一个穷人的版本来说明如何Counter使用字典和dict.get(k, [,d])尝试获取密钥 ( k) 的方法,但如果它没有' t 存在它返回默认值而不是 ( d):

>>> list1 = [
         ('12392', 'some string', 'some other string'),
         ('12392', 'some new string', 'some other string'),
         ('7862', None, 'some other string')
]
>>> d = {}
>>> for x, y, z in list1:
        d[x] = d.get(x, 0) + 1


>>> d
{'12392': 2, '7862': 1}

回答by Mosqueteiro

I needed some extra functionality that Counter didn't have. I have a list of tuples that the first element is the key and the second element is the amount to add. @jamylak solution was a great adaptation for this!

我需要一些 Counter 没有的额外功能。我有一个元组列表,第一个元素是键,第二个元素是要添加的数量。@jamylak 解决方案是一个很好的改编!

>>> list = [(0,5), (3,2), (2,1), (0,2), (3,4)]

>>> d = {}
>>> for x, y in list1:
    d[x] = d.get(x, 0) + y

>>> d
{0: 7, 2: 1, 3: 6}