[英]“'NoneType' object is not iterable” when the code works fine for others. How do I figure out what's wrong?
I'm following a guided project in Python and there's code I wrote that seems to align with the solution, however, I'm getting an error while they did not. 我正在遵循Python中的指导项目,并且我编写的代码似乎与解决方案一致,但是,当他们没有时,我会收到错误。
I saw online that a return statement might be needed but the solution doesn't use one and no matter where I place the return, I get an error anyway. 我在网上看到可能需要一个return语句,但解决方案不使用一个,无论我在哪里放回,我总是得到一个错误。
"displayfreq"
is a code I defined above in the code; "displayfreq"
是我在代码中定义的代码; it produces a sorted frequency table. 它产生一个排序的频率表。
genres_ios = displayfreq(ios_free, -5)
for genre in genres_ios:
total = 0
len_genre = 0
for app in ios_free:
genre_app = app[-5]
if genre_app == genre:
tot_ratings = float(app[5])
total += tot_ratings
len_genre += 1
avg_tot_rating = total / len_genre
print(genre, 'with average total rating of', avg_tot_ratings)
I expected to see the average number of ratings per genre, but instead, I'm getting, 我希望看到每种类型的平均评分数,但相反,我得到了,
"TypeError: 'NoneType' object is not iterable"
“TypeError:'NoneType'对象不可迭代”
for the line "for genre in genres_ios"
对于
"for genre in genres_ios"
这一行
A return statement is needed in displayfreq()
, or it will return None
. 需要 return语句中
displayfreq()
或者将返回None
。 Because genres_ios
is None
, you cannot iterate over it and you get the error. 因为
genres_ios
是None
,所以你不能迭代它并且你得到错误。
If it works on other machines, displayfreq()
might not work for your machine. 如果它适用于其他计算机,则
displayfreq()
可能不适用于您的计算机。
As you specified that you are getting "TypeError: 'NoneType' object is not iterable" for the line " for genre in genres_ios: ...", it means that the variable genres_ios is having value None and thus you are getting such an error. 正如您指定的那样,对于“genres_ios中的 类型: ”行, “TypeError:'NoneType'对象不可迭代 ”,这意味着变量genres_ios的值为None ,因此您会收到这样的错误。
For this, you need to return the variable or expression of your sorted frequency table. 为此,您需要返回已排序频率表的变量或表达式。
Also note that in the function displayfreq, you are not manipulating the ios_free variable or you would have the value of ios_free changed. 另请注意,在函数displayfreq中,您没有操作ios_free变量,或者您将更改ios_free的值。 If you want a copy of ios_free use ios_free.copy() .
如果你想要ios_free的副本,请使用ios_free.copy() 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.