你可以使用
itertools.groupby()
来帮助:
from itertools import groupby
def count_runs(list_of_values, threshold_value=1.0, minimum_count=4):
count = 0
for k, g in groupby(list_of_values, key=lambda x: x >= threshold_value):
if k:
g = list(g)
if len(g) >= minimum_count:
count += len(g)
return count
>>> count_runs([2.0, 2.0, 2.0, 0.0, 0, 0, 2.0, 2.0, 2.0, 0, 0])
0
>>> count_runs([2.0, 2.0, 2.0, 2.0, 0, 0, 2.0, 2.0, 2.0, 0, 0])
4
>>> count_runs([2.0, 2.0, 2.0, 2.0, 0, 0, 3.0, 2.0, 2.0, 2.0, 10.0, 0, 0])
9
这将提供在每个包含
minimum_count
个或更多值的组中超过阈值的值的计数。请注意,它处理符合标准的多个组。
例如,上一个示例的
groupby()
将返回以下内容:
>>> list_of_values = [2.0, 2.0, 2.0, 2.0, 0, 0, 3.0, 2.0, 2.0, 2.0, 10.0, 0, 0]
>>> for k, g in groupby(list_of_values, key=lambda x: x >= threshold_value):
... print(k, list(g))
...
True [2.0, 2.0, 2.0, 2.0]
False [0, 0]
True [3.0, 2.0, 2.0, 2.0, 10.0]
False [0, 0]
任何一个包含1个或更多的值且大于等于阈值的组将出现在键为
True
的组中。只有长度大于等于最小计数的组才会进一步考虑,其中它的长度将与其他这样的组一起计算。
这段代码可以更简洁地编写,但可读性会降低,如下所示:
def count_runs(list_of_values, threshold_value=1.0, minimum_count=4):
return sum(count for count in (len(list(g)) for k, g in groupby(list_of_values, key=lambda x: x >= threshold_value) if k) if count >= minimum_count)
list_of_values
的第一项是1.0
,那么结果应该是什么? - RomanPerekhrest[2.0, 2.0, 2.0, 2.0, 0, 0, 3.0, 2.0, 2.0, 2.0, 10.0, 0, 0]
,那么结果应该是4、5还是9呢? - mhawke