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)
添加回答
举报