Discuss / Python / next()函数调用方法的一点注意

next()函数调用方法的一点注意

Topic source

第一种方法:

>>> next(( x for x in range(3)))
0
>>> next(( x for x in range(3)))
0
>>> next(( x for x in range(3)))
0

第二种方法:

>>> L = ( x for x in range(3))
>>> next(L)
0
>>> next(L)
1
>>> next(L)
2
>>> next(L)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

两种调用next()函数的方法得到的结果截然不同!!

廖雪峰

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

你的第一种方法创建了3个不同的对象,每次都取第一个,当然总是0

不要轻易怀疑python语言本身,要坚信是自己代码有问题


  • 1

Reply