简体   繁体   中英

How do I use 2 variables in a Python for loop in the recommended Pythonic way?

I have the following for loop in C that I want to mimic in Python:

for (index = 0; index < n; ++index)
{
    for (i = 0, j = index; j < n; ++i, ++j)
    {
         'do something'
    }
}

Is there a more elegant/Pythonic way to do this, or do I have to declare a variable outside of the loop like so:

for index in range(m):
    i = 0
    for j in range(index, m):
        'do something'
        i += 1

It's hard to say without knowing more about what is going in the second loop, but as it's written I would say:

for index in range(n):
    for i,j in enumerate(range(index,n)):
        'do something'

would be the way you'd do that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM