我知道这个错误消息'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我希望我的代码在没有错误消息的情况下执行相同的输出。你知道名单的哪一部分可能没有吗?谢谢您:)
发布于 2020-03-29 00:50:44
在nextYear中缺少一个返回语句。
你的职能应该是:
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))
return next_heights..。至少从我对您希望nextYear做什么的理解来看。在任何情况下,您都需要一个返回语句。
我的产出是:
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
38 50 28 48 53 37 40 51 53 44 46为了澄清这一点,None来自于您的nextYear函数的返回。
在您的行printList(nextYear(heights))中,nextYear(heights)返回None,这将传递给printList。
https://stackoverflow.com/questions/60908868
复制相似问题