为什么函数的整数返回值与该整数的解释不同
Why is integer returnvalue of function not interpreted the same as that integer
为什么这样做有效?
def nextSquare():
i = 1;
# An Infinite loop to generate squares
while True:
yield i*i
i += 1 # Next execution resumes
# from this point
# Driver code to test above generator
# function
for num in nextSquare():
if num > 100:
break
print(num)
但不是这个?
def nextSquare():
i = 1;
# An Infinite loop to generate squares
while True:
yield i*i
i += 1 # Next execution resumes
# from this point
# Driver code to test above generator
# function
for num in 1:
if num > 100:
break
print(num)
nextsquare每次返回一个整数运行所以nextsquare第一次returns和
有什么区别
for num in nextSquare():
和
for num in 1:
An integer is returned each time nextsquare is run
对了,nextSquare
应该是“运行”在前。你称它为 nextSquare()
,它 returns 是一个可迭代对象,然后 for
循环遍历它,像这样:
retval = nextSquare()
it = iter(retval)
num = next(it)
while True:
# loop body
try:
num = next(it)
except StopIteration:
break
但是,调用 next(1)
没有意义,因为迭代单个数字没有意义 - 循环迭代 collections 或类似“collection-like”的东西。一个数字肯定不像 collection,所以你不能遍历它。
错误消息正是这样说的:
>>> for _ in 1:
... ...
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
为什么这样做有效?
def nextSquare():
i = 1;
# An Infinite loop to generate squares
while True:
yield i*i
i += 1 # Next execution resumes
# from this point
# Driver code to test above generator
# function
for num in nextSquare():
if num > 100:
break
print(num)
但不是这个?
def nextSquare():
i = 1;
# An Infinite loop to generate squares
while True:
yield i*i
i += 1 # Next execution resumes
# from this point
# Driver code to test above generator
# function
for num in 1:
if num > 100:
break
print(num)
nextsquare每次返回一个整数运行所以nextsquare第一次returns和
有什么区别for num in nextSquare():
和
for num in 1:
An integer is returned each time nextsquare is run
对了,nextSquare
应该是“运行”在前。你称它为 nextSquare()
,它 returns 是一个可迭代对象,然后 for
循环遍历它,像这样:
retval = nextSquare()
it = iter(retval)
num = next(it)
while True:
# loop body
try:
num = next(it)
except StopIteration:
break
但是,调用 next(1)
没有意义,因为迭代单个数字没有意义 - 循环迭代 collections 或类似“collection-like”的东西。一个数字肯定不像 collection,所以你不能遍历它。
错误消息正是这样说的:
>>> for _ in 1:
... ...
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable