>>> def find_repeats(L, num_repeats):
... idx = 0
... while idx < len(L):
... if [L[idx]]*num_repeats == L[idx:idx+num_repeats]:
... L[idx:idx+num_repeats] = [True]*num_repeats
... idx += num_repeats
... else:
... idx += 1
... return L
...
>>> L=[1,1,1,4,6]
>>> print find_repeats(L, 2)
[True, True, 1, 4, 6]
>>> L=[1,1,1,4,6]
>>> print find_repeats(L, 3)
[True, True, True, 4, 6]
>>>
这是一个版本,它允许您指定应匹配的数字并在第一次替换后停止。
>>> def find_repeats(L, required_number, num_repeats, stop_after_match=False):
... idx = 0
... while idx < len(L):
... if [required_number]*num_repeats == L[idx:idx+num_repeats]:
... L[idx:idx+num_repeats] = [True]*num_repeats
... idx += num_repeats
... if stop_after_match:
... break
... else:
... idx += 1
... return L
...
>>> L=[1,1,1,4,6]
>>> print find_repeats(L, 1, 2)
[True, True, 1, 4, 6]
>>> L=[1,1,1,4,6]
>>> print find_repeats(L, 1, 3)
[True, True, True, 4, 6]
>>> L=[1,1,1,4,4,4,6]
>>> print find_repeats(L, 1, 3)
[True, True, True, 4, 4, 4, 6]
>>> L=[1,1,1,4,4,4,6]
>>> print find_repeats(L, 4, 3)
[1, 1, 1, True, True, True, 6]