简体   繁体   English

每次迭代的更改范围均始于Python“ for循环”

[英]Change range start in Python 'for loop' for each iteration

I'm a novice and learning python (using 2.7). 我是新手,正在学习python(使用2.7)。 I'm attempting some simple scripts to test how python handles different types of loops. 我正在尝试一些简单的脚本来测试python如何处理不同类型的循环。

My question is: can python change the starting point of the "range" function on each iteration if the start point is assigned to a variable? 我的问题是:如果将起点分配给变量,python是否可以在每次迭代中更改“范围”函数的起点? Here is an example of my code: 这是我的代码示例:

def build(n, period):
    n2 = n
    for digit in range(int(n2), 20):
        print "At the top i is %d" % n
        digit += period
        numbers.append(digit)

        print "Numbers now:", numbers
        print "At the bottom i is %d" % digit

        print "The Numbers:"
        n2 += period

        for num in numbers:
            print num


key = raw_input("Press 1 to call function \"build\", press any other key to quit.")
if key == "1":
    i = raw_input("What integer is our start value?")
    amt = raw_input("What is the common difference?")
    numbers = [int(i)]
    build(int(i),int(amt))

else:
    quit()

I tried to use a second local variable 'n2' inside the function so I could keep the initial value of 'n' constant and then redefine the range for each iteration. 我尝试在函数内使用第二个局部变量'n2',以便可以将'n'的初始值保持不变,然后为每次迭代重新定义范围。 The very first number in the appended list moves by the common difference but after that it always steps by +1 integer. 附加列表中的第一个数字移动相同的差,但此后总是递增+1整数。 I can easily make this happen with a 'while' loop but curious if a 'for' loop can be used to accomplish this? 我可以通过“ while”循环轻松实现这一点,但很好奇是否可以使用“ for”循环来完成此操作吗?

range creates a fixed list the moment you call that function at the beginning of your for loop. range在for循环开始时调用该函数时会创建一个固定列表。 You can think of the top of the for loop as assigning n2 to the next element of that list no matter what you do inside the loop. 您可以将for循环的顶部视为将n2分配给该列表的下一个元素,无论您在循环中进行什么操作。 If you want to change the period of the range, use the third argument: 如果要更改范围的周期,请使用第三个参数:

range(n, 20, period)

will move in steps of size period through the range instead of steps of size one. 将在整个范围内以大小period的步长而不是大小1的步长移动。

It won't work in a way you expect. 它不会以您期望的方式工作。 Expression range(int(n2), 20) gets evaluated only one time in the beginning of for-loop. 表达式range(int(n2), 20)在for循环开始时仅被评估一次。 You can't change the scope of a for-loop that way. 您不能以这种方式更改for循环的范围。

What you can modify is a step parameter in range function, but it does not change your starting point - it only defines what is the next element in the iteration process. 您可以修改的是range函数中的step参数,但不会更改您的起点-它仅定义迭代过程中的下一个元素。

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

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