【发布时间】:2012-01-25 18:37:00
【问题描述】:
当我在 for 循环中使用生成器时,它似乎“知道”,当没有更多元素产生时。现在,我必须使用没有 for 循环的生成器,并手动使用 next() 来获取下一个元素。我的问题是,我怎么知道是否没有更多元素?
我只知道:next() 引发异常(StopIteration),如果什么都没有,那么对于这样一个简单的问题,BUT 是不是有点太“重”了?难道没有has_next()之类的方法吗?
以下几行应该清楚我的意思:
#!/usr/bin/python3
# define a list of some objects
bar = ['abc', 123, None, True, 456.789]
# our primitive generator
def foo(bar):
for b in bar:
yield b
# iterate, using the generator above
print('--- TEST A (for loop) ---')
for baz in foo(bar):
print(baz)
print()
# assign a new iterator to a variable
foobar = foo(bar)
print('--- TEST B (try-except) ---')
while True:
try:
print(foobar.__next__())
except StopIteration:
break
print()
# assign a new iterator to a variable
foobar = foo(bar)
# display generator members
print('--- GENERATOR MEMBERS ---')
print(', '.join(dir(foobar)))
输出如下:
--- TEST A (for loop) ---
abc
123
None
True
456.789
--- TEST B (try-except) ---
abc
123
None
True
456.789
--- GENERATOR MEMBERS ---
__class__, __delattr__, __doc__, __eq__, __format__, __ge__, __getattribute__, __gt__, __hash__, __init__, __iter__, __le__, __lt__, __name__, __ne__, __new__, __next__, __reduce__, __reduce_ex__, __repr__, __setattr__, __sizeof__, __str__, __subclasshook__, close, gi_code, gi_frame, gi_running, send, throw
感谢大家,祝您有美好的一天! :)
【问题讨论】:
标签: python-3.x iteration generator yield next