pythonic way to do something N times without an index variable?

前端 未结 8 1174
一整个雨季
一整个雨季 2020-12-02 08:11

Every day I love python more and more.

Today, I was writing some code like:

for i in xrange(N):
    do_something()

I had to do som

相关标签:
8条回答
  • 2020-12-02 08:54

    Use the _ variable, as I learned when I asked this question, for example:

    # A long way to do integer exponentiation
    num = 2
    power = 3
    product = 1
    for _ in xrange(power):
        product *= num
    print product
    
    0 讨论(0)
  • 2020-12-02 08:57

    I just use for _ in range(n), it's straight to the point. It's going to generate the entire list for huge numbers in Python 2, but if you're using Python 3 it's not a problem.

    0 讨论(0)
提交回复
热议问题