这是我的代码:
def extractEachKth(inputArray, k):
n = []
for i in inputArray:
n.append(i)
for i in range(1, len(n) + 1):
if i % k == 0:
n.remove(n[i-1])
return (n)
print (extractEachKth([1,2,3,4,5,6,7,8,9,10],3))
这是我的错误:
Traceback (most recent call last):
File "C:/Users/Harry/Documents/randompythonprograms/editable.py", line 9, in <module>
print (extractEachKth([1,2,3,4,5,6,7,8,9,10],3))
File "C:/Users/Harry/Documents/randompythonprograms/editable.py", line 7, in extractEachKth
n.remove(n[i-1])
IndexError: list index out of range
答案 0 :(得分:0)
这个:n.remove(n[i-1])
导致问题,因为你要从列表中删除值并循环到len(n)
所以它不会有相同的大小,即列表的长度将减少并且将会给你index out of bound error
,你的范围是正确的。
您可以在删除值时更新N
来解决此问题,如下所示:
def extractEachKth(inputArray, k):
n = []
for i in inputArray:
n.append(i)
i = 1
N = len(n) + 1
while i < N:
if i % k == 0:
n.remove(n[i-1])
N = len(n) + 1
# or simply
# N -= 1
i += 1
return (n)
print (extractEachKth([1,2,3,4,5,6,7,8,9,10],3))