What is the most pythonic way to have a generator expression executed?

后端 未结 4 1386
礼貌的吻别
礼貌的吻别 2021-01-03 06:22

More and more features of Python move to be \"lazy executable\", like generator expressions and other kind of iterators. Sometimes, however, I see myself wanting to roll a o

4条回答
  •  佛祖请我去吃肉
    2021-01-03 07:08

    There are many accumulators which have the effect of consuming the whole iterable they're given, such as min or max -- but even they don't ignore entirely the results yielded in the process (min and max, for example, will raise an exception if some of the results are complex numbers). I don't think there's a built-in accumulator that does exactly what you want -- you'll have to write (and add to your personal stash of tiny utility function) a tiny utility function such as

    def consume(iterable):
        for item in iterable: pass
    

    The main reason, I guess, is that Python has a for statement and you're supposed to use it when it fits like a glove (i.e., for the cases you'd want consume for;-).

    BTW, a.write returns None, which is falsish, so any will actually consume it (and a.writelines will do even better!). But I realize you were just giving that as an example;-).

提交回复
热议问题