Найти индексы последовательных элементов в списках - PullRequest
1 голос
/ 08 апреля 2020

Я хочу взять список вроде:

x = [1,2,2,3,4,6,6]

и вернуть 2d список с индексами повторяющихся значений:

[ [1,2], [5,6]]

Я пробовал следующее:

new_list = []
i = 0
while i < len(x)-1:
    if x[i] == x[i+1]:
        new_list.append([x[i],x[i+1]]
    i += 1

x не обязательно отсортировано, но имеет хотя бы одну серию повторяющихся значений. Например, x также может быть:

x = [1,4,2,3,3,3,7,0]

Ответы [ 4 ]

0 голосов
/ 08 апреля 2020

Вы можете использовать itertools.groupby здесь.

from itertools import groupby
x=[1, 2, 2, 2, 3, 3, 4, 4, 6, 6, 6, 6, 6, 6, 8]
ranges=[list(g) for _,g in groupby(range(len(x)),lambda idx:x[idx])]
# [[0], [1, 2, 3], [4, 5], [6, 7], [8, 9, 10, 11, 12, 13], [14]]
#   1    2  2  2    3  3    4  4    6  6  6   6   6   6     8

final=[[r[0],r[-1]] for r in ranges if len(r)>1]
# [[1, 3], [4, 5], [6, 7], [8, 13]]

Чистый Python подход:

x=[1, 2, 2, 2, 3, 3, 4, 4, 6, 6, 6, 6, 6, 6, 8]
out=[]
count=0
for i in range(1,len(x)):
    prev=x[i-1]
    if x[i]==prev:
        count+=1
    elif count and x[i]!=prev:
        out.append([i-count-1,i-1])
        count=0
if count:
    out.append([i-count,i])

out
# [[1, 3], [4, 5], [6, 7], [8, 13]]
0 голосов
/ 08 апреля 2020

Вы можете отслеживать текущий индекс и, когда следующий элемент равен значению значения в current_index, вы добавляете его к результату, но вам нужно увеличивать значение индекса, пока его значение не станет другим

x = [1, 2, 2, 3, 4, 6, 6]

result = []
cur_idx = 0
i = 1

while i < len(x):
    if x[cur_idx] == x[i]:
        result.append([cur_idx, x[cur_idx]])

        # Increase value of i up to the index where there is different value
        while i < len(x):
            if x[cur_idx] != x[i]:
                # Set cur_idx to the index of different value
                cur_idx = i
                i += 1
                break
            i += 1
    else:
        cur_idx = i
        i += 1

print(result)
# [[1, 3], [5, 3]]
0 голосов
/ 08 апреля 2020

Попробуйте этот код:

# Hello World program in Python
x = [1,2,2,3,4,6,6]
new_list = []
i = 0
indexes = []
while i < len(x)-1:
    if x[i] == x[i+1]:
        indexes.append(i)
        indexes.append(i+1)
    else:
        indexes = list(set(indexes))
        if len(indexes) != 0:
            new_list.append(indexes)
        indexes = []
    i+=1

indexes = list(set(indexes))
if len(indexes) != 0:
    new_list.append(indexes)
print(new_list)

Результат:

[[1, 2], [5, 6]]
0 голосов
/ 08 апреля 2020

Попробуйте это.

def repeating_values( initital_list):
    cache = {}
    result = []
    for i, element in enumerate(initital_list):
        if element in cache:
            result.append([cache[initital_list[i]], i])
        else:
            cache[element] = i

    return result 

Для вашего ввода


x = [1,2,2,3,4,6,6]

print(repeating_values(x))

Результат

[[1, 2], [5, 6]]
...