例如,如果我做了如下事情:
def test():
yield from range(100)
testing = test()
iter(testing)
如果iter
函数返回一个迭代器,但函数调用的结果没有分配给变量,为什么运行print(list(testing))
或类似的函数会返回所有值?我以为改装发电机会消耗里面的东西.
例如,如果我做了如下事情:
def test():
yield from range(100)
testing = test()
iter(testing)
如果iter
函数返回一个迭代器,但函数调用的结果没有分配给变量,为什么运行print(list(testing))
或类似的函数会返回所有值?我以为改装发电机会消耗里面的东西.
不,iter()函数不使用迭代器;相反,它返回的迭代器保持不变.
以下是所有对象的名称及其作用:
def test(): # generator creation function
yield from range(100)
testing = test() # generator/iterator object
t2 = iter(testing) # t2 and testing are identical
list(testing) # runs the iterator to exhaustion
list(testing) # this time you get an empty list
生成器对象是一种迭代器.他们只向前跑一次.调用next(it)
将检索一个值并使迭代器前进.调用iter(it)
返回相同的迭代器.要创建一个新的迭代器,只需再次调用生成器创建函数:testing2 = test()
.