简体   繁体   English

计算所有满足条件的Python

[英]Count all that satisfy a condition in Python

Is there a way to add all that satisfy a condition in a shorthand nested loop? 有没有一种方法可以在速记嵌套循环中添加所有满足条件的内容? My following attempt was unsuccessful: 我的以下尝试未成功:

count += 1 if n == fresh for n in buckets['actual'][e] else 0

Use sum with a generator expression: sum与生成器表达式一起使用:

sum(n == fresh for n in buckets['actual'][e])

as True == 1 and False == 0 , so else is not required. 因为True == 1False == 0 ,所以不需要else


Related reads: Is it Pythonic to use bools as ints? 相关阅读: 将布尔值用作整数是否为Pythonic? , Is False == 0 and True == 1 in Python an implementation detail or is it guaranteed by the language? Python中的False == 0和True == 1是实现细节还是由语言保证?

Using sum() function: 使用sum()函数:

sum(1 if n == fresh else 0  for n in buckets['actual'][e])

or: 要么:

sum(1 for n in buckets['actual'][e] if n == fresh)

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

相关问题 断言列表中的所有项目都满足 Python 中的条件 - Assert that all the items in a list satisfy a condition in Python Python IF条件不满足,但它输入了脚本。 Numpy any()和all()问题 - Python IF condition is not satisfy but it enter the script. Numpy any() and all() issue 每行不满足条件的值的计数 - Count of values per row that do not satisfy a condition 满足给定条件的列表中连续元素的计数 - Count of consecutive elements in a list that satisfy a given condition 如何在python中使用pandas计算满足某些条件的日期范围内的天数 - How to count number of days in a date range which satisfy some condition using pandas in python 检查列表中的所有元素是否满足条件 - checking if all elements in a list satisfy a condition 选择所有列上满足相同条件的行 - select the rows that satisfy the same condition on all columns 如何在 Python 中找到满足条件(最大和最小阈值)的所有可能组合? - How to find all possible combinations that satisfy a condition (max and min threshold) in Python? Python - 获取列表的索引,所有进一步的条目都满足条件 - Python - get index of list from which on all further entries satisfy condition 计算列表中满足特定条件的值 - Count how many values in a list that satisfy certain condition
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM