Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
226 views
in Technique[技术] by (71.8m points)

python - How to Pythonically yield all values from a list?

Suppose I have a list that I wish not to return but to yield values from. What is the most pythonic way to do that?

Here is what I mean. Thanks to some non-lazy computation I have computed the list ['a', 'b', 'c', 'd'], but my code through the project uses lazy computation, so I'd like to yield values from my function instead of returning the whole list.

I currently wrote it as following:

my_list = ['a', 'b', 'c', 'd']
for item in my_list:
    yield item

But this doesn't feel pythonic to me.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Since this question doesn't specify; I'll provide an answer that applies in Python >= 3.3

If you need only to return that list, do as Anurag suggests, but if for some reason the function in question really needs to be a generator, you can delegate to another generator; suppose you want to suffix the result list, but only if the list is first exhausted.

def foo():
    list_ = ['a', 'b', 'c', 'd']
    yield from list_

    if something:
        yield this
        yield that
        yield something_else

In versions of python prior to 3.3, though, you cannot use this syntax; you'll have to use the code as in the question, with a for loop and single yield statement in the body.

Alternatively; you can wrap the generators in a regular function and return the chained result: This also has the advantage of working in python 2 and 3

from itertools import chain

def foo():
    list_ = ['a', 'b', 'c', 'd']

    def _foo_suffix():
        if something:
            yield this
            yield that
            yield something_else

    return chain(list_, _foo_suffix())

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...