Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/316.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在python中使用pop()函数去除偶数_Python - Fatal编程技术网

如何在python中使用pop()函数去除偶数

如何在python中使用pop()函数去除偶数,python,Python,例如,以下代码: list1 = [23, 3, 6, 5, 12, 9, 7, 4] remove_even_list(list1) print(list1) 印刷品 [23, 3, 5, 9, 7] 以下是我编写的代码: def remove_even_list(numbers): for index in range(len(numbers)-1,-1,-1): if numbers[index] % 2 == 0: numbers.po

例如,以下代码:

list1 = [23, 3, 6, 5, 12, 9, 7, 4]
remove_even_list(list1)
print(list1)
印刷品

[23, 3, 5, 9, 7]
以下是我编写的代码:

def remove_even_list(numbers):
    for index in range(len(numbers)-1,-1,-1):
        if numbers[index] % 2 == 0:
            numbers.pop[index]

def test_remove_even_list():    
    list1 = [23, 3, 6, 5, 12, 9, 7, 4]
    remove_even_list(list1)
    print(list1)

它能跑,但什么也跑不动。请帮我找出上面的错误。非常感谢。

您刚刚犯了一个简单的错误

numbers.pop[index]
应该是

numbers.pop(index)

你的问题不完全是关于它的,但是这个过滤器没有循环过滤偶数

list1 = [23, 3, 6, 5, 12, 9, 7, 4]    
print(list(filter(lambda x: x % 2, list1)))


你所说的“它可以运行,但什么也不运行”是什么意思?如果你感兴趣,
reverse
的可能副本非常适合在列表中迭代。例如
对于索引,枚举中的元素(反转(数字))
如果元素%2==0:
numbers.pop(index)
运行代码,我会得到消息
TypeError:“内置函数”或“方法”对象没有属性“\uu getitem\uuuuuuuuuuuuuuuuuuuuuuu”
。我知道您没有得到想要的输出,我也知道错误消息对您来说很难理解。但是报告错误消息很重要,即使您不理解它,因为它可以帮助我们帮助您。
list1 = [23, 3, 6, 5, 12, 9, 7, 4]
print([x for x in list1 if(x % 2 !=0)])
list1 = [23, 3, 6, 5, 12, 9, 7, 4]
print([x for x in list1 if x % 2])