我想从我的列表中弹出某些项目。这是我的代码:
lst = [1,2,3,4,5,6,7,8,9]
popVal = [0, 5, 8]
for i in popVal:
lst.pop(i)
预期输出应[2,3,4,5,7,8]
为 index 0
,5
并8
从lst
但是,我收到一个错误:
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
IndexError: pop index out of range
如果我打印我的列表,这就是输出
[2, 3, 4, 5, 6, 8, 9]
每次弹出一个元素时,列表都会缩小。因此,例如,以前在索引 8 处的内容,现在在索引 3 处。
假设您的列表popVal
是严格升序的,则以下修改后的代码将起作用
lst = [1,2,3,4,5,6,7,8,9]
popVal = [0, 5, 8]
for n, i in enumerate(popVal):
lst.pop(i - n)
这确保了随着列表缩小,要从中弹出的索引也会相应缩小。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句