如何连续计算文本文件的结果
How to count in a row results from text file
我想知道如何计算文本文件中的连续结果。我写了这段代码:
from itertools import groupby
def count_runs_of(seq, val):
return sum(key == val for key, group in groupby(seq))
示例:
>>> count_runs_of([1, 2, 3, 3, 3, 1, 2, 2, 4], 3)
1
>>> count_runs_of([1, 2, 3, 3, 3, 1, 2, 2, 4, 3, 3], 3)
2
>>> count_runs_of([1, 2, 3, 3, 3, 1, 2, 2, 4, 3, 3, 9, 2, 4, 3, 3, 3], 3)
3
>>> count_runs_of([1, 2, 3, 3, 3, 1, 2, 2, 4], 2)
2
我想知道意甲有多长。例如,当我在第一个结果中有“1”时,我还想打印“3”(因为连续有 3 x 3)。你可以帮帮我吗?谢谢
def count_runs_of(seq, val):
return [len(list(group)) for key, group in groupby(seq) if key == val]
示例
>>> count_runs_of([1, 2, 3, 3, 3, 1, 2, 2, 4, 3, 3], 3)
[3, 2]
你已经非常接近了,你可以通过使用 sum()
和生成器表达式对其进行循环来获得组的长度。这将 return 列表中所有此类运行的长度:
>>> def count_runs_of(seq, val):
return [sum(1 for _ in g) for k, g in groupby(seq) if k == val]
...
>>> count_runs_of([1, 2, 3, 3, 3, 1, 2, 2, 4], 3)
[3]
>>> count_runs_of([1, 2, 3, 3, 3, 1, 2, 2, 4, 3, 3], 3)
[3, 2]
我想知道如何计算文本文件中的连续结果。我写了这段代码:
from itertools import groupby
def count_runs_of(seq, val):
return sum(key == val for key, group in groupby(seq))
示例:
>>> count_runs_of([1, 2, 3, 3, 3, 1, 2, 2, 4], 3)
1
>>> count_runs_of([1, 2, 3, 3, 3, 1, 2, 2, 4, 3, 3], 3)
2
>>> count_runs_of([1, 2, 3, 3, 3, 1, 2, 2, 4, 3, 3, 9, 2, 4, 3, 3, 3], 3)
3
>>> count_runs_of([1, 2, 3, 3, 3, 1, 2, 2, 4], 2)
2
我想知道意甲有多长。例如,当我在第一个结果中有“1”时,我还想打印“3”(因为连续有 3 x 3)。你可以帮帮我吗?谢谢
def count_runs_of(seq, val):
return [len(list(group)) for key, group in groupby(seq) if key == val]
示例
>>> count_runs_of([1, 2, 3, 3, 3, 1, 2, 2, 4, 3, 3], 3)
[3, 2]
你已经非常接近了,你可以通过使用 sum()
和生成器表达式对其进行循环来获得组的长度。这将 return 列表中所有此类运行的长度:
>>> def count_runs_of(seq, val):
return [sum(1 for _ in g) for k, g in groupby(seq) if k == val]
...
>>> count_runs_of([1, 2, 3, 3, 3, 1, 2, 2, 4], 3)
[3]
>>> count_runs_of([1, 2, 3, 3, 3, 1, 2, 2, 4, 3, 3], 3)
[3, 2]