当前实现如何避免索引超出范围错误?

How to avoid index out of range error with current implementation?

我得到了一个名为 nums 的整数列表,我正在尝试删除所有出现的值 (val)。我试图查看 valnums 的索引匹配的位置,并试图将其从列表中删除。但是,我不断收到“列表索引超出范围”错误。我猜这是因为当我弹出匹配 valnums 元素时,它缩小了列表,因此它超出了范围。难道不能以这种方式删除所有出现的值吗?

nums = [3,2,2,3]
val = 2
for i in range(len(nums)):
    if val == nums[i]:
        nums.pop(i)
print(nums)

您不应在遍历列表时尝试从列表中删除元素,因为内存在您访问它时会发生变化。

相反,您应该创建一个新列表:

nums = [3,2,2,3]
val = 2
print([num for num in nums if val != num]) # Prints [3, 3]

使用 remove 方法从列表中删除值

nums = [3,2,2,3]
val = 2
l = list(nums)#creating new list
for v in l:
    if v == val:
        nums.remove(val)#removing values

print(nums)

输出:

$ python3 file.py 
[3, 3]