python 出错 'int' object is not iterable

t=0
W=[2,2,2,3,3,3,5,5,5,5,8,8]
UW=[2,3,5,8]
Tfit=[12,24,25]
for j in range(len(UW)):

t = t+sum(W.count(UW[j])*max(Tfit)/len(W))

错误提示:Traceback (most recent call last):
File "C:/Users/zb/Desktop/compute.py", line 6, in <module>

t = t+sum(W.count(UW[j])*max(Tfit)/len(W))

TypeError: 'float' object is not iterable
去掉“/len(W)”时,显示:TypeError: 'int' object is not iterable

阅读 9.6k
2 个回答

如果t每次for循环都要加进去,这么写

In [4]: t=0
   ...: W=[2,2,2,3,3,3,5,5,5,5,8,8]
   ...: UW=[2,3,5,8]
   ...: Tfit=[12,24,25]
   ...: item_list = []
   ...: for j in range(len(UW)):
   ...:     item_list.append(W.count(UW[j])*max(Tfit)/len(W))
   ...:     t = t + sum(item_list)

如果t不需要在for循环内部加,这么写

In [1]: t=0
   ...: W=[2,2,2,3,3,3,5,5,5,5,8,8]
   ...: UW=[2,3,5,8]
   ...: Tfit=[12,24,25]
   ...: item_list = []
   ...: for j in range(len(UW)):
   ...:     item_list.append(W.count(UW[j])*max(Tfit)/len(W))
   ...:
   ...: t = t+sum(item_list)

W.count(UW[j]) 返回的是一个 int 类型的数字,sum 方法需要传入可迭代的对象。

Signature: sum(iterable, start=0, /)
Docstring:
Return the sum of a 'start' value (default: 0) plus an iterable of numbers

When the iterable is empty, return the start value.
This function is intended specifically for use with numeric values and may
reject non-numeric types.
Type:      builtin_function_or_method
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题