Discuss / Python / 关于next()的使用

关于next()的使用

Topic source

Iris_3218

#1 Created at ... [Delete] [Delete and Lock User]

我定义了这么一个函数:

>>> def num():
        n=0
        while True:
        yield(n)
        n=n+1

然后:

>>> a=num()
>>> next()
0
>>> next()
1
>>> next()
3

此时结果正常,但如果这样:

>>> next(num())
0
>>> next(num())
0
>>> next(num())
0

输出的始终是第一个值,请问这是为什么?

next(num())#调用一次num(),于是生成0
next(num())#重新调用一次num(),于是生成0
next(num())#又重新调用一次num(),于是生成0

相当于创建了三个不同的对象

Tonight_dou

#4 Created at ... [Delete] [Delete and Lock User]
每次next()作用于不同的对象

Gnayiewnib

#5 Created at ... [Delete] [Delete and Lock User]

我觉得你可以把它理解为对生成器的用next函数调用的规则,在生成器那章

poppylb

#6 Created at ... [Delete] [Delete and Lock User]

a=num() next(num()) ==>next(a)

a的所有取值可以看作一个List??

会不会和C一样?默认为初始地址了

LSJOP

#7 Created at ... [Delete] [Delete and Lock User]
def num():
    n = 0
    while True:
        yield n
        n = n + 1

第四行代码应该是yield n 而不是yield (n)

while 后面循环格式错误 yeild 和 n=n+1 都再空四格。

你这段代码错误好多。。。多亏自己打一遍


  • 1

Reply