序列的第一个和最后一个索引
First and last index of a sequence
我有兴趣在至少三个相同数字(它们必须连续)的序列中找到第一个和最后一个索引。如果有更多序列,索引(开始-结束)将附加到列表中。例子:
s = [1,1,1,1,4,1,1,1] --> output: [0,3,5,7]
s = [1,1,1,1,4,1,1,1]
c = []
indexes = []
for i in range(len(s)):
if s.count(s[i]) >= 3:
c.append(i)
my output: [0, 1, 2, 3, 5, 6, 7]
在这里,尝试使用此代码来解决您的问题:
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)
您可以使用 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]
。
我有兴趣在至少三个相同数字(它们必须连续)的序列中找到第一个和最后一个索引。如果有更多序列,索引(开始-结束)将附加到列表中。例子:
s = [1,1,1,1,4,1,1,1] --> output: [0,3,5,7]
s = [1,1,1,1,4,1,1,1]
c = []
indexes = []
for i in range(len(s)):
if s.count(s[i]) >= 3:
c.append(i)
my output: [0, 1, 2, 3, 5, 6, 7]
在这里,尝试使用此代码来解决您的问题:
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)
您可以使用 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]
。