Python 3.x:测试生成器是否剩余元素 [英] Python 3.x: Test if generator has elements remaining

查看:241
本文介绍了Python 3.x:测试生成器是否剩余元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在for循环中使用生成器时,它似乎知道,当没有更多的元素产生时。现在,我必须使用没有for循环的生成器,并手动使用 next ()来获取下一个元素。我的问题是,我怎么知道,如果没有更多元素?

When I use a generator in a for loop, it seems to "know", when there are no more elements yielded. Now, I have to use a generator WITHOUT a for loop, and use next() by hand, to get the next element. My problem is, how do I know, if there are no more elements?

我只知道: next ()引发异常(StopIteration) ),如果没有什么可以留下的,但对于这样一个简单的问题,这也不是一个例外吗?是不是像 has_next ()那样的方法?

I know only: next() raises an exception (StopIteration), if there is nothing left, BUT isn't an exception a little bit too "heavy" for such a simple problem? Isn't there a method like has_next() or so?

以下几行应该清楚,我的意思是:

The following lines should make clear, what I mean:

#!/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

感谢大家,祝你有个美好的一天! :)

Thanks to everybody, and have a nice day! :)

推荐答案

你写的两个语句都是以完全相同的方式查找生成器的结尾。 for循环只调用.next(),直到引发StopIteration异常,然后终止。

The two statements you wrote deal with finding the end of the generator in exactly the same way. The for-loop simply calls .next() until the StopIteration exception is raised and then it terminates.

http://docs.python.org/tutorial/classes.html#iterators

因此我不喜欢我认为等待StopIteration异常是处理问题的'重'方式,它是设计使用的生成器的方式。

As such I don't think waiting for the StopIteration exception is a 'heavy' way to deal with the problem, it's the way that generators are designed to be used.

这篇关于Python 3.x:测试生成器是否剩余元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆