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

我有兴趣在至少三个相同数字的序列上找到第一个和最后一个索引(它们必须排成一行)。如果有更多序列,索引(开始-结束)将附加到列表中。例子: 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顺序


慕雪6442864
浏览 101回答 2
2回答

呼如林

你可以使用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 = 0for 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_lengthprint(positions)这会给你想要的结果[0, 3, 5, 7]。

慕丝7291255

在这里,尝试使用此代码来解决您的问题:prev_value = s[0]prev_index = 0consecutive_count = 0for 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 = indexif consecutive_count > 2:    indexes.append(prev_index)    indexes.append(index)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python