类型错误:“int"对象不可迭代 [英] TypeError: 'int' object is not iterable
问题描述
执行此代码时出错-
for i in len(str_list):类型错误:int"对象不可迭代
我该如何解决?(Python 3)
How would I fix it? (Python 3)
def str_avg(str):
str_list=str.split()
str_sum=0
for i in len(str_list):
str_sum += len(str_list[i])
return str_sum/i
推荐答案
您正在尝试在整数中循环;len()
返回一.
You are trying to loop over in integer; len()
returns one.
如果您必须在整数序列上生成循环,请使用 range()
对象:
If you must produce a loop over a sequence of integers, use a range()
object:
for i in range(len(str_list)):
# ...
通过将 len(str_list)
结果传递给 range()
,你得到一个从零到 str_list
长度的序列,减一(因为不包括最终值).
By passing in the len(str_list)
result to range()
, you get a sequence from zero to the length of str_list
, minus one (as the end value is not included).
请注意,现在您的 i
值将是用于计算平均值的不正确值,因为它比实际值小一列表长度!你想除以len(str_list)
:
Note that now your i
value will be the incorrect value to use to calculate an average, because it is one smaller than the actual list length! You want to divide by len(str_list)
:
return str_sum / len(str_list)
但是,无需在 Python 中执行此操作.您遍历列表本身的元素.这消除了首先创建索引的需要:
However, there is no need to do this in Python. You loop over the elements of the list itself. That removes the need to create an index first:
for elem in str_list
str_sum += len(elem)
return str_sum / len(str_list)
所有这些都可以用 sum() 在一行中表达
函数,顺便说一句:
All this can be expressed in one line with the sum()
function, by the way:
def str_avg(s):
str_list = s.split()
return sum(len(w) for w in str_list) / len(str_list)
我用s
替换了名称str
;最好不要屏蔽内置类型名称,否则可能会导致稍后出现混淆错误.
I replaced the name str
with s
; better not mask the built-in type name, that could lead to confusing errors later on.
这篇关于类型错误:“int"对象不可迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!