2 回答

TA貢獻1798條經驗 獲得超3個贊
你可以使用groupby
.?讓我們從以下內容開始:
s = [1, 1, 1, 1, 4, 1, 1, 1]
for value, group in itertools.groupby(s):
? ? # print(value)
? ? print(list(group))
這會給你
[1, 1, 1, 1]
[4]
[1, 1, 1]
現在讓我們添加您的條件并跟蹤當前位置。
s = [1, 1, 1, 1, 4, 1, 1, 1]
positions = []
current_position = 0
for value, group in itertools.groupby(s):
? ? group_length = len(list(group))
? ? if group_length >= 3:
? ? ? ? positions.extend([current_position, current_position + group_length - 1])
? ? current_position += group_length
print(positions)
這會給你想要的結果[0, 3, 5, 7]。

TA貢獻1859條經驗 獲得超6個贊
在這里,嘗試使用此代碼來解決您的問題:
prev_value = s[0]
prev_index = 0
consecutive_count = 0
for index, value in enumerate(s):
if value == prev_value:
consecutive_count += 1
else:
if consecutive_count > 2:
indexes.append(prev_index)
indexes.append(index - 1)
consecutive_count = 1
prev_value = value
prev_index = index
if consecutive_count > 2:
indexes.append(prev_index)
indexes.append(index)
添加回答
舉報