[英]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布尔值(
False
和True
)是int
和False
== 0
和True
== 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.