gpt4 book ai didi

python - 为什么从列表中删除内容时我的索引没有改变?

转载 作者:行者123 更新时间:2023-12-03 23:46:53 25 4
gpt4 key购买 nike

def remove_middle(lst, start, end):
i = 0
x = start + i
while i < end:
lst.remove(lst[x])
i +=1
return lst



print(remove_middle([4, 8, 15, 16, 23, 42], 1, 3))

Output:

[4,23,42]


因此,当删除第一个项目 (8) 时, i 增加到 1 并且 start = 2。但是按照这个逻辑,接下来将删除 16,因为 lst[2] 点中没有 8。从那里,42 应该在 i = 2, x = 3 时被删除,并且 8/16 消失会将 42 放在 lst[3] 位置。

那么是否保留了初始索引?还是有其他事情发生?

最佳答案

因为当你添加到 i , x没有被改变,因为你没有重新定义 xstart + 1 :

def remove_middle(lst, start, end):
i = 0
while i < end:
x = start + i
lst.remove(lst[x])
i +=1
return lst

print(remove_middle([4, 8, 15, 16, 23, 42], 1, 3))

输出:
Traceback (most recent call last):
File "C:/Users/Caitlin/Desktop/p.py", line 9, in <module>
print(remove_middle([4, 8, 15, 16, 23, 42], 1, 3))
File "C:/Users/Caitlin/Desktop/p.py", line 5, in remove_middle
lst.remove(lst[x])
IndexError: list index out of range

关于python - 为什么从列表中删除内容时我的索引没有改变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62183539/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com