我想列出一个列表:
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]
尝试
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
您可以跟踪当前索引,并且当下一个元素等于current_index中的值时,可以将其追加到结果中,但是需要增加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]]
尝试此代码: