TypeError:“NoneType”对象不可迭代

编码器1234

我知道这个错误消息 'TypeError: 'NoneType' object is not iterable' 意味着没有数据。但是,我正在查看我的所有列表,并且没有任何部分没有值元素。这是与我的问题相关的代码部分。

def printList(heights):
    print(" ".join(str(h) for h in heights))


def nextYear(heights):
    next_heights = []
    for i in range(len(heights)):
        next_heights.append(heights[i] + 5)
        i += 1
    print(" ".join(str(h) for h in next_heights))

#main routine

heights = [33, 45, 23, 43, 48, 32, 35, 46, 48, 39, 41]
printList(heights)
print("Predicted heights after a year")
printList(nextYear(heights))

这是我的代码输出:

33 45 23 43 48 32 35 46 48 39 41
Predicted heights after a year
38 50 28 48 53 37 40 51 53 44 46
Traceback (most recent call last):
  File "/Users/ellarendell/Desktop/test.py", line 17, in <module>
    printList(nextYear(heights))
  File "/Users/ellarendell/Desktop/test.py", line 2, in printList
    print(" ".join(str(h) for h in heights))
TypeError: 'NoneType' object is not iterable

我希望我的代码在没有错误消息的情况下执行相同的输出。你知道列表的哪一部分可以有“无”吗?谢谢 :)

kareem_emad

您的代码有两处错误:

  • 首先你没有next_heights在你的函数中返回
def nextYear(heights):
    next_heights = []
    for i in range(len(heights)):
        next_heights.append(heights[i] + 5)
        i += 1
    return next_heights

如果没有返回行,它将返回None并将其传递给printList函数,您也不需要在内部打印,nextYear因为您已经printList在函数返回亮点后调用打印

  • 第二件事是增加迭代器,你真的不能这样做,你可以试试这个小例子来理解我的意思
for i in range(10):
  print(i)
  i +=15555

所以首先要做的是从循环中删除这一行

def nextYear(heights):
    next_heights = []
    for i in range(len(heights)):
        next_heights.append(heights[i] + 5)
    return next_heights

它会在每次迭代时自动增加,如果您希望它增加 2 而不是 1,那么您可以在range()函数中将其指定为步长。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

**TypeError:“NoneType”对象不可迭代**

Python - TypeError:“NoneType”对象不可迭代

TypeError:“ NoneType”对象在Python中不可迭代

TypeError:“ NoneType”对象不可迭代pyscreeze

TypeError:“ NoneType”对象不可迭代WTForms FieldSelect

无法解决“NoneType”对象不可迭代的TypeError

-- TypeError: 无法解包不可迭代的 NoneType 对象

NoneType 对象不可迭代

“ NoneType”对象不可迭代

TypeError: 'NoneType' 对象不可迭代(h5 文件)

列表的Python问题(TypeError:“ NoneType”对象不可迭代)

Scrapy代码引发TypeError:“ NoneType”对象不可迭代

TypeError: 'NoneType' 对象在覆盖旧值时不可迭代

TypeError:无法解压缩不可迭代的NoneType对象

Python递归函数:TypeError:'NoneType'对象不可迭代

`TypeError:`subprocess.call` 中的“NoneType”对象不可迭代

TypeError:使用zip_longest时,“ NoneType”对象不可迭代

Python TypeError:“ NoneType”对象不可迭代,但定义了每个变量

熊猫read_sql中的“ TypeError:'NoneType'对象不可迭代”

遍历Python列表获取TypeError:'NoneType'对象不可迭代

TypeError: 'NoneType' 对象不可迭代从初学者 2

NoneType对象不可迭代错误

TypeError对象不可迭代

在ExtraTreesClassifier中显示为NoneType的feature_importances_:TypeError:'NoneType'对象不可迭代

Flask TypeError:“ NoneType”类型的参数不可迭代

如何修复 TypeError:“NoneType”不可迭代?

TypeError:“ RegexValidator”对象不可迭代

TypeError:“ ShuffleSplit”对象不可迭代

TypeError:“ KFold”对象不可迭代