Is there a way to repeat a certain number of times without entering an unnecessary variable?

If I want to iterate ntimes in Java, I write:

for (i = 0; i < n; i++) {
    // do stuff
}

In Python, there seems to be a standard way to do this:

for x in range(n):
    # do stuff

As always, Python is more concise and readable. But it xbothers me, as it is not necessary, and PyDev generates a warning, as it is xnever used.

Is there a way to do this that does not generate any warnings or introduce unnecessary variables?

+5
source share
2 answers

Python ( ) _ , , .

, in Python , - .

( , PyDev _).

+6

Python .

for i in range(10):

, . range . i - , .

, , .

cpu, , :

push x
loop:
    do something
    increment x
    jump if x > y
    goto loop

JIT , , , . , , python .

:

  4           0 SETUP_LOOP              20 (to 23) 
              3 LOAD_GLOBAL              0 (range) 
              6 LOAD_FAST                0 (x) 
              9 CALL_FUNCTION            1 
             12 GET_ITER             
        >>   13 FOR_ITER                 6 (to 22) 
             16 STORE_FAST               1 (i) 

  5          19 JUMP_ABSOLUTE           13 
        >>   22 POP_BLOCK            

, . , StopIteration, ( 23).

, , x . , - () StopIteration for . , python for-loop - -, for-each Java. .

: i, j k . - .

+2

All Articles