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

后端 未结 4 1387
礼貌的吻别
礼貌的吻别 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 06:53

    There is one obvious way to do it, and that is the way you should do it. There is no excuse for doing it a clever way.

    a = open("numbers.txt", "w")
    for i in xrange(100):
        a.write("%d " % i)
    d.close()
    

    Lazy execution gives you a serious benefit: It allows you to pass a sequence to another piece of code without having to hold the entire thing in memory. It is for the creation of efficient sequences as data types.

    In this case, you do not want lazy execution. You want execution. You can just ... execute. With a for loop.

提交回复
热议问题