More Pythonic Way to Run a Process X Times

后端 未结 5 1217
忘了有多久
忘了有多久 2020-12-23 15:46

Which is more pythonic?

While loop:

count = 0
while count < 50:
    print \"Some thing\"
    count = count + 1

5条回答
  •  感动是毒
    2020-12-23 16:11

    There is not a really pythonic way of repeating something. However, it is a better way:

    map(lambda index:do_something(), xrange(10))
    

    If you need to pass the index then:

    map(lambda index:do_something(index), xrange(10))
    

    Consider that it returns the results as a collection. So, if you need to collect the results it can help.

提交回复
热议问题