简体   繁体   English

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

[英]Count occurrences of some value in list of lists of tuples

I have a list that looks like this : 我有一个看起来像这样的清单:

fruit_list = [
    ['fruit1', ('banana',  '1234'), ('pear', '3456'), ('banana', '4578')],
    ['fruit2', ('apple',  '5474'), ('mango', '7854')],
    ['fruit3', ('Pineapple',  '4534'), ('apple', '5456'), ('apple', '4458')],
] 

What I would like to know is given a particular fruit and a particular list within that list, if that fruit appears more than once. 我想知道的是,如果该水果出现不止一次,则会得到一个特定的水果和该列表中的特定列表。

Something like fruit_list[0].count('banana') > 1 , but I don't think that will work because of the tuples. 诸如fruit_list[0].count('banana') > 1 ,但由于元组,我认为这不起作用。

You could use the sum() function with a generator expression to count matching tuples: 您可以使用带有生成器表达式的sum()函数来计算匹配的元组:

sum(t[0] == 'banana' for t in fruit_list[0]) > 1

This works because python booleans ( False and True ) are a subclass of int and False == 0 and True == 1 . 这是可行的,因为python布尔值( FalseTrue )是intFalse == 0True == 1的子类。 Summing those gives you the count of matches: 将这些内容相加即可得出匹配的数量:

>>> fruit_list = [
...     ['fruit1', ('banana',  '1234'), ('pear', '3456'), ('banana', '4578')],
...     ['fruit2', ('apple',  '5474'), ('mango', '7854')],
...     ['fruit3', ('Pineapple',  '4534'), ('apple', '5456'), ('apple', '4458')],
... ]
>>> sum(t[0] == 'banana' for t in fruit_list[0])
2
>>> sum(t[0] == 'banana' for t in fruit_list[0]) > 1
True

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 计算元组列表出现的次数 - Count number of occurrences of list of tuples 计算元组列表中的出现次数 - Count occurrences within a list of list of tuples 计算字典列表中某个值的出现次数 - Count Occurrences of a Value in a List of Dictionaries 如何计算字典列表中特定字典键的出现次数,一些字典值包含列表和 append 计数值 - How to count occurrences of a specific dict key in dicts list and some dicts values ​contains list and append the count in value 列表列表中的元组中count元素=“” - count elements = “” in tuples inside a list of lists Python:如何计算元组列表中的出现次数? - Python: how can I count the occurrences in a list of tuples? 按第一个值对带有元组的列表进行排序 - Sort list of lists with tuples by first value Python:如何遍历两个列表中的每个值,计算在第一个列表中值&lt;22或在第二个列表中&lt;27的出现次数? - Python: How to iterate through each value in two lists, count the occurrences that value is < 22 in the 1st list OR < 27 in the 2nd list? 如何在列表列表中选择一些项目并检查它是否存在于元组列表中 - How to pick some items in list of lists and check if it exists in list of tuples 用键和值按字典计算列表中出现的次数 - count number of occurrences in list by dict with key and value
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM