gpt4 book ai didi

Python - "' NoneType'对象不可迭代“错误

转载 作者:行者123 更新时间:2023-11-28 21:19:03 25 4
gpt4 key购买 nike

我在 codecademy 项目中的指示是

Define a function called purify that takes in a list of numbers, removes all odd numbers in the list, and returns the result. For example, purify([1,2,3]) should return [2]. Do not directly modify the list you are given as input; instead, return a new list with only the even numbers.

我想出的代码是:

def purify(numbers):

pure = numbers

for num in pure:
if num % 2 != 0:
pure = pure.remove(num)

return pure

错误是:

Oops, try again. Your function crashed on [1] as input because your function throws a "'NoneType' object is not iterable" error.

据我了解,这意味着我的代码中的某些内容返回为“无”。或者那里没有数据。我似乎找不到这个简短代码有什么问题,除非它在我的 if 语句中。提前致谢。

所以我在代码中进行了编辑以删除“pure = pure.remove(num)”,这解决了 none 问题。然而,当运行代码时,它仍然无法输入 [4,5,5,4] 并返回 [4,5,4]。

新代码:

def purify(numbers):

pure = numbers

for num in pure:
if num % 2 != 0:
pure.remove(num)

return pure

最佳答案

第一个问题是您在遍历列表时更改列表。 DO NOT change lists while you are iterating over them.您会错过循环中的一些值。

第二个问题是 list.remove 就地执行并返回 None。因此,当您执行 pure = pure.remove(num) 时,您将 pure 设置为 None,这不再是可迭代的,这反过来是导致错误的原因。相反,您可以按如下方式过滤列表

def purify(numbers):
return [num for num in numbers if num % 2 == 0]

关于Python - "' NoneType'对象不可迭代“错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25334394/

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