为了账号安全,请及时绑定邮箱和手机立即绑定

序列的第一个和最后一个索引

序列的第一个和最后一个索引

慕雪6442864 2023-08-22 17:18:43
我有兴趣在至少三个相同数字的序列上找到第一个和最后一个索引(它们必须排成一行)。如果有更多序列,索引(开始-结束)将附加到列表中。例子: 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]Python顺序
查看完整描述

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]。


查看完整回答
反对 回复 2023-08-22
?
慕丝7291255

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)


查看完整回答
反对 回复 2023-08-22
  • 2 回答
  • 0 关注
  • 96 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信