python - TypeError : “NoneType” object is not iterable

标签 python list compiler-errors

我知道此错误消息“TypeError:'NoneType'对象不可迭代”表示没有数据。但是,我正在浏览所有列表,没有任何部分没有值元素。
这是我代码中与我的问题相关的部分。

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

我希望我的代码执行相同的输出而不会出现错误消息。
您知道列表的哪一部分可能没有“None”吗?
谢谢 :)

最佳答案

您的代码有两点错误:

  • 首先,您不会在函数
  • 中返回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()函数中将其指定为步长。

    关于python - TypeError : “NoneType” object is not iterable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60908868/

    相关文章:

    python - 仅当连续 nan 超过 x 时才进行掩码

    c++ - 当通知迭代器参数初始化为空列表的开头时,list::insert 的行为是什么?

    C 代码编译错误

    c++ - 为什么在这种情况下不隐式生成 operator= 和复制构造函数?

    python - Django admin - 限制下拉列表中的选择

    python - 根据给定值查找列表中字典项的索引号

    具有列表本地和全局范围的 Python 奇怪的东西

    html - 使 <ul> 列表响应 - 最后一个 <li> 不向左浮动

    java - 列表/界面问题

    python - 使用 AES 在 C 中加密并在 Python 中解密