Python: yield-and-delete

后端 未结 4 1846
逝去的感伤
逝去的感伤 2021-02-02 15:45

How do I yield an object from a generator and forget it immediately, so that it doesn\'t take up memory?

For example, in the following function:

def grou         


        
4条回答
  •  萌比男神i
    2021-02-02 16:30

    The function grouper as defined has the artifact of creating wasteful duplicates because you have wrapped a function of no effect around itertools.islice. The solution is to delete your redundant code.

    I think there are concessions to C derived languages which are non-Pythonic and are causing excess overhead. For example, you have

    i = iter(iterable)
    itertools.islice(i)
    

    Why does i exist? iter will not cast a non-iterable into an iterable, there aren't such casts. If given a non-iterable, both of those lines would generate an exception; the first does not guard the second.

    islice will happliy act as and iterator (although may give economies that a yield statement won't. You've got too much code: grouper probably need not exist.

提交回复
热议问题