How to Pythonically yield all values from a list?

后端 未结 4 1056
青春惊慌失措
青春惊慌失措 2020-12-16 08:46

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 comp

相关标签:
4条回答
  • 2020-12-16 09:35

    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())
    
    0 讨论(0)
  • 2020-12-16 09:37

    Best Pythonically way to do this task is

    In [1]: my_list = ['a', 'b', 'c', 'd']
    
    In [2]: (x for x in my_list)
    Out[2]: <generator object <genexpr> at 0x7fd9e4fdc230>
    
    0 讨论(0)
  • 2020-12-16 09:41

    Use iter to create a list iterator e.g.

    return iter(List)
    

    though if you already have a list, you can just return that, which will be more efficient.

    0 讨论(0)
  • 2020-12-16 09:43

    You can build a generator by saying

    (x for x in List)
    
    0 讨论(0)
提交回复
热议问题