Python "for loop and def" 练习并得到 "TypeError: 'int' object is not iterable"
Posted
技术标签:
【中文标题】Python "for loop and def" 练习并得到 "TypeError: \'int\' object is not iterable"【英文标题】:Python "for loop and def" practice and got "TypeError: 'int' object is not iterable"Python "for loop and def" 练习并得到 "TypeError: 'int' object is not iterable" 【发布时间】:2020-07-20 10:47:18 【问题描述】:这是我的编码如下。
import random
import math
def count_hit_in_cirle(iteration):
randX=random.uniform(-1.0,1.0) # returns a X random float in INclusive [-1.0, 1.0]
randY=random.uniform(-1.0,1.0) # returns a y random float in INclusive [-1.0, 1.0]
one_if_in_circle=0
for i in range(iteration):
def one_if_in_circle(randX, randY):
if math.sqrt(randX*randX+randY*randY) <= 1:
return 1
else:
return 0
return (sum(one_if_in_circle(randX, randY)))
count_hit_in_cirle(1000)
但是我得到了这样的错误:
count_hit_in_cirle(1000)
Traceback (most recent call last):
File "<ipython-input-4-4dcc579bc645>", line 1, in <module>
count_hit_in_cirle(1000)
File "<ipython-input-3-4fbc77f1c9ec>", line 11, in count_hit_in_cirle
return (sum(one_if_in_circle(randX, randY)))
TypeError: 'int' object is not iterable
然后我尝试了:
return (sum(one_if_in_circle(randX, randY)))
我还是有错误:
"TypeError: 'function' 对象不可迭代"
有没有人可以告诉我如何修复我的编码?非常感谢
【问题讨论】:
【参考方案1】:您似乎正在尝试创建一个生成器。您需要将循环放在函数内部,而不是围绕它,并使用yield
而不是return
。
def count_hit_in_cirle(iteration):
randX=random.uniform(-1.0,1.0) # returns a X random float in INclusive [-1.0, 1.0]
randY=random.uniform(-1.0,1.0) # returns a y random float in INclusive [-1.0, 1.0]
one_if_in_circle=0
def one_if_in_circle(randX, randY):
for i in range(iteration):
if math.sqrt(randX*randX+randY*randY) <= 1:
yield 1
else:
yield 0
return (sum(one_if_in_circle(randX, randY)))
您的函数只返回一个整数,而不是 sum()
可以迭代的序列。
【讨论】:
非常感谢。它有效,但结果仍然不是我所期望的。我需要编辑所有编码结构,但感谢您澄清收益和回报之间的区别。【参考方案2】:one_if_in_circle 在one_if_in_circle=0
中定义为int 类型变量,在def one_if_in_circle(randX, randY)
中定义为函数。换一个。
【讨论】:
以上是关于Python "for loop and def" 练习并得到 "TypeError: 'int' object is not iterable"的主要内容,如果未能解决你的问题,请参考以下文章
python怎样用最简单的for loop求list中的最大值
高效实现:Java 中的“Python For Else Loop”
代码中输入数字自动筛选出最大值,使用array,for loop and if (21.9.2017)
No loop matching the specified signature and casting was found for ufunc gre