简体   繁体   English

如何在 python 中循环步进和计数

[英]how to loop step and count in python

I want to be able to count 5 at every step of 2 while condition is less than 1000 for example:当条件小于 1000 时,我希望能够在 2 的每一步中数 5,例如:

i = 0
j = 2000
k = 3000
while i < 1000:
    i += 2
    for x in range(5):
        print(i)
    j += 2
    for x in range(5):
        print(j)
    k += 2
    for x in range(5):
        print(k)

but the output just print i, j, k 5 times但是 output 只打印 i、j、k 5 次

output:::
2
2
2
2
2
2002
2002
2002
2002
2002
3002
3002
3002
3002
3002
4
4
4

I want the the result to be: .....我希望结果是:......

2
3
4
5
6
2002
2003
2004
2005
2006
3002
3003
3004
3005
3006
8      #please note here that 8(i) continue by 2 steps from 6
9
10
etc..........

i will like to know a more simpler and pythonic way to do this.我想知道一种更简单和pythonic的方法来做到这一点。 Thanks谢谢

That's a weird thing you're trying to do, but here is my modified version with your desired output:这是您尝试做的一件奇怪的事情,但这是我的修改版本,带有您想要的 output:

a, b, c = 0, 2000, 3000
for i in range(2, 1000, 6):
    for x in range(5):
        print(a+i+x)
    for x in range(5):
        print(b+i+x)
    for x in range(5):
        print(c+i+x)

So you're trying to get number progression, here's one way to do it:因此,您正在尝试获得数字进展,这是一种方法:

progression = [a for a in range(2,7)] \
            + [b for b in range(2002,2007)] \
            + [c for c in range(3002,3007)]
for i in range(0, 1000, 6):
    for p in progression:
        print(p + i)

2
3
4
5
6
2002
2003
2004
2005
2006
3002
3003
3004
3005
3006
8
9
10
11
12
2008
2009
2010
2011
2012
3008
3009
3010
3011
3012
14
15
16
17
18
2014
2015
2016
2017
2018
3014
3015
3016
3017
3018
20
21
22
23
24
2020
2021
2022
2023
2024
3020
3021
3022
3023
3024
26
...<truncated>

You can do this in other ways but here is solution for your approach您可以通过其他方式执行此操作,但这里是您的方法的解决方案

i = 0
j = 2000
k = 3000
while i < 1000:
    i += 2
    for x in range(5):
        print(i)
        if x < 4:
            i += 1

    j += 2
    for x in range(5):
        print(j)
        if x < 4:
            j += 1

    k += 2
    for x in range(5):
        print(k)
        if x < 4:
            k += 1

I don't really undestand what you want to do but this output what you want:我真的不明白你想做什么,但是这个 output 你想要什么:

i = 0
j = 2000
k = 3000
while i < 1000:
    i += 2
    for x in range(5):
        print(i+x)
    j += 2
    for x in range(5):
        print(j+x)
    k += 2
    for x in range(5):
        print(k+x)
    i += 4

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

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