python yield and stopiteration in one loop?

后端 未结 2 949
温柔的废话
温柔的废话 2021-02-07 02:52

i have a generator where i would like to add an initial and final value to the actual content, it\'s something like this:

# any generic queue where i would like          


        
2条回答
  •  萌比男神i
    2021-02-07 03:21

    You seem to be overcomplicating this quite a bit:

    >>> q = [1, 2, 3, 4]
    >>> def gen(header='something', footer='anything'):
            yield header
            for thing in q:
                yield thing
            yield footer
    
    
    >>> for tmp in gen():
            print(tmp)
    
    
    something
    1
    2
    3
    4
    anything
    

    StopIteration will automatically be raised when a generator stops yielding. It's part of the protocol of how generators work. Unless you're doing something very complex, you don't need to (and shouldn't) deal with StopIteration at all. Just yield each value you want to return from the generator in turn, then let the function return.

提交回复
热议问题