【问题标题】:Why is integer returnvalue of function not interpreted the same as that integer为什么函数的整数返回值与该整数不同
【发布时间】:2021-05-04 20:49:07
【问题描述】:

为什么会这样?

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第一次返回的区别是什么

for num in nextSquare():

for num in 1:

【问题讨论】:

  • 这是一个非常抽象的问题。你想要一个解决方案,还是一个 python 实现和设计权衡讨论?
  • 这能回答你的问题吗? What does the "yield" keyword do?

标签: python-3.x for-loop yield


【解决方案1】:

nextsquare 每次运行都会返回一个整数

对,nextSquare 应该先“运行”。你把它称为nextSquare(),它返回一个可迭代对象,然后for 循环遍历它,像这样:

retval = nextSquare()
it = iter(retval)
num = next(it)
while True:
    # loop body
    try:
        num = next(it)
    except StopIteration:
        break

但是,调用 next(1) 没有意义,因为迭代一个数字没有意义 - 循环迭代 collections 或“类似集合”的东西”。单个数字当然不像集合,因此您不能对其进行迭代。

错误消息准确地说:

>>> for _ in 1:
...  ...
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-28
    • 2014-06-05
    • 2013-04-14
    • 1970-01-01
    • 1970-01-01
    • 2011-06-02
    • 1970-01-01
    • 2014-11-02
    相关资源
    最近更新 更多