【发布时间】:2020-12-31 02:57:00
【问题描述】:
我正在尝试查找列表中重复的位置范围。
例如,在列表中l = [1, 1, 2, 2, 2, 2, 3, 3, 3, 4, 5, 6,7,7, 7] 2 在位置 2 和 5 之间重复。我的代码一直工作到最后,错误是由我假设的内部循环没有跟踪数组的长度引起的。
我应该如何解决这个错误?
代码:
l = [1, 1, 2, 2, 2, 2, 3, 3, 3, 4, 5, 6,7,7, 7]
i = 0
out = []
while i < (len(l)):
ogPos = i
ogVal = l[i]
while (l[i] == ogVal):
print(i)
i += 1
edPos = i-1
print(f'\t{ogPos}\t{edPos}\t{ogVal}')
输出:
0
1
0 1 1
2
3
4
5
2 5 2
6
7
8
6 8 3
9
9 9 4
10
10 10 5
11
11 11 6
12
13
14
Traceback (most recent call last):
File "testlist.py", line 8, in <module>
while (l[i] == ogVal):
IndexError: list index out of range
【问题讨论】: