查找列表中连续项的索引

2024-04-25 13:08:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我想列一个如下的清单:

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

并返回一个二维列表,其中包含重复值的索引:

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

Tags: 方法列表newlenif排序listappend
3条回答

可以跟踪当前索引,当下一个元素等于当前_索引中的值时,可以将其附加到结果中,但需要增加索引的值,直到其值不同为止

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

试试这个

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

请尝试以下代码:

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

相关问题 更多 >