对于您的特定用例,19被False覆盖.在第二个循环开始之前,我添加了一个小的回退/理智判断.你可以通过我的print
个日志(log)看到发生了什么:
def m(n: int, l: list):
# set i to its max value
broke_out = False
for i, v in enumerate(l):
if v % n == 0 and v != n and v != False:
print(f"breaking on index :{i}")
broke_out = True
break
# SANITY CHECK: if we never broke out of the above loop and we're on the last index, we're done.
if not broke_out and i == len(l)-1:
return l
# now use i as the starting point in this loop
for x in range(i, len(l), n):
# if not isinstance(x, int):
print(f"about to overwrite l[x] which is: {l[x]} where x is: {x}")
# if l[x] % n == 0:
l[x] = False
print(f"State of l before returning : {l}")
return l
l = list(range(10, 20))
for i in range(2, 20):
m(i, l)
print(l)
完整输出:
breaking on index :0
about to overwrite l[x] which is: 10 where x is: 0
about to overwrite l[x] which is: 12 where x is: 2
about to overwrite l[x] which is: 14 where x is: 4
about to overwrite l[x] which is: 16 where x is: 6
about to overwrite l[x] which is: 18 where x is: 8
State of l before returning : [False, 11, False, 13, False, 15, False, 17, False, 19]
breaking on index :5
about to overwrite l[x] which is: 15 where x is: 5
about to overwrite l[x] which is: False where x is: 8
State of l before returning : [False, 11, False, 13, False, False, False, 17, False, 19]
[False, 11, False, 13, False, False, False, 17, False, 19]
[Finished in 0.1s]