python-3.x 为什么remove方法不能正确地移除数组中元素的所有占位符?

s5a0g9ez  于 4个月前  发布在  Python
关注(0)|答案(1)|浏览(62)

此问题在此处已有答案

Strange result when removing item from a list while iterating over it in Python(12个答案)
cannot remove the last element of a python list [duplicate](1个答案)
3天前关闭。
我得到一个数组和一个值。我必须删除给定数组中所有的值。
我写的代码不适用于这个测试用例。

*数组=[0,1,2,2,3,0,4,2]
*值=2
我的代码:

def removeElement(nums, val):
        for i in nums:
            if i==val:
                nums.remove(i)
        return nums

字符串
预期输出:[0,1,3,0,4]
我的输出:[0,1,3,0,4,2]
为什么最后一个2没有被删除?

o4hqfura

o4hqfura1#

我假设你使用while in方法是这样的:

array = [0,1,2,2,3,0,4,2]

def removeElement(value, array):
    while int(value) in array:
        array.remove(int(value))
    return array

print(delete_value(2, array))

字符串
您的代码不工作的原因是here,基本上您不应该编辑用作输入使用迭代的同一个数组
它之所以有效,是因为我们对它说,我们要删除 * 值 *,而不是索引2,并将array.remove(int(value))中常用的方括号[]替换为圆括号()

相关问题