简体   繁体   English

如何以推荐的Python方式在Python for循环中使用2个变量?

[英]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: 我在C中有以下要在Python中模仿的for loop

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: 有没有更优雅的/ Pythonic的方式来做到这一点,或者我必须像这样在循环外声明一个变量:

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. 将是您这样做的方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在Pythonic while循环中执行迭代名称/变量的替代方法 - Alternate way to do Iterative name/variables in Pythonic while loop 如何在具有range()的循环中使用变量? (蟒蛇) - How do I use variables in a loop with range()? (Python) Python2.7如何在循环中使用多重变量? - Python2.7 how do I use multiples variables in a loop? 如何以pythonic的方式做到这一点? - How to do this in a pythonic way? 在循环中更新多个 class 变量的 Pythonic 方法? - Pythonic way to update multiple class variables in a loop? 如何以 pythonic 方式对 class 的不同属性使用相同的 getter 和 setter 属性和函数? - How do I use same getter and setter properties and functions for different attributes of a class the pythonic way? PYTHON:如何以最 Python 的方式将两个字典合并到一个列表中 - PYTHON: How do i merge two dictionaries inside a list in the most pythonic way 如何以一种快速和 Pythonic 的方式在 python pandas 中适应和使用 Excel 的 Sumif function? - How can I adapt and use Excel's Sumif function in python pandas in a way that is fast and pythonic? 什么是使用私有变量的Pythonic方法? - What is the Pythonic way to use private variables? 如何以更详尽、更高效和 Pythonic 的方式编写 for 循环 - How can I write a for loop in a more elaborative and efficient and pythonic way
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM