简体   繁体   English

使循环迭代从第一次迭代的结束值继续

[英]For loop iteration to continue from the end value of first iteration

I am looking for an output in the following manner: If my inputs are 我正在以以下方式寻找输出:如果我的输入是

starting_value = 8
ending_value = 20

I want output as 我想输出为

8 13    ##8+(5) = 13
14 19   ##start of next iteration should be 13+1 = 14, and then 14+(5)

I wrote a for loop for this: 我为此写了一个for循环:

for i in range(8,20):
    start = i
    end = i+5
    print(start,end)
    i = end+1

But I'm getting wrong result: 但是我得到了错误的结果:

8 13
9 14
10 15
11 16
12 17
13 18
14 19
15 20
16 21
17 22
18 23
19 24

Is there something wrong in my for loop, Any better pythonic way to do this? 我的for循环中有问题吗,有什么更好的pythonic方式吗?

You can do that by using a step size of 6 in your range: 您可以通过在范围内使用6步长来实现:

starting_value = 8
ending_value = 20
step = 5

for i in range(starting_value, ending_value, step + 1):
    start = i
    end = i + step
    print(start,end)

Output: 输出:

8 13
14 19

Simple shifting: 简单的转移:

for i in range(8, 20, 6):
    print(i, i+5)

The output: 输出:

8 13
14 19

The same with predefined variables: 与预定义变量相同:

start, end, step = 8, 20, 5

for i in range(start, end, step+1):
    print(i, i + step)

try this: 尝试这个:

i = 8
while i <20:
    start = i
    end = i+5
    print(start,end)
    i = end+1

output: 输出:

8 13
14 19

Here is my take on it: 这是我的看法:

starting_value = 8
ending_value = 20

start = starting_value
end = starting_value
while end+1 < ending_value:
  end = start + 5
  print(start, end)
  start = end + 1

Output: 输出:

8 13
14 19

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

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