亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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

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

慕雪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 關注
  • 188 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號