简体   繁体   English

如何在 python 的 for 循环中插入 if 条件

[英]How to insert an if condition in a for loop in python

I want to do a for loop and explain it here by simple print function.我想做一个for循环,在这里通过简单的打印function来解释。 I want change the data printed after a fixed value.我想更改固定值后打印的数据。 Let's regard this code:让我们看看这段代码:

for i in range (7):
    print (i, i+15, i+1)

it gives me:它给了我:

0 15 1
1 16 2
2 17 3
3 18 4
4 19 5
5 20 6
6 21 7

But I want to add 1 to the printed values of the second row after each 3 interation.但我想在每3次交互后将1添加到第二行的打印值。 I mean from the first to third iteration, I want the same results as printed above.我的意思是从第一次迭代到第三次迭代,我想要与上面打印的相同的结果。 But from third to sixth I want to add 1 to i+15 (printing i+16 rather than i+15 ).但是从第三到第六我想将1添加到i+15 (打印i+16而不是i+15 )。 Then again after the sixth row, I want to add 1 to i+16 (printing i+17 rather than i+16 or i+15 ).然后在第六行之后,我想将1添加到i+16 (打印i+17而不是i+16i+15 )。 I mean I want to have this one:我的意思是我想要这个:

0 15 1
1 16 2
2 17 3
3 19 4
4 20 5
5 21 6
6 23 7

How can I make my i in the function to e such a thing?我怎样才能让我在 function 中的i变成这样的东西? Itried the following but it gives another thing: Itried 以下但它给出了另一件事:

for i in range (7):
    if i % 3 == 0:
        print (i, i+15+1, i+1)
    else:
        print (i, i+15, i+1)

I do appreciate any help in advance.我非常感谢您提前提供的任何帮助。

Try this:尝试这个:

for i in range (7):
    print (i, i//3+i+15, i+1)

0 15 1
1 16 2
2 17 3
3 19 4
4 20 5
5 21 6
6 23 7

For ranges that don't start from 0, to keep the same logic (increment every 3 iterations) you can do the following:对于不是从 0 开始的范围,要保持相同的逻辑(每 3 次迭代递增),您可以执行以下操作:

for i in range (4,15):
        print (i, (i-4)//3+i+15, i+1)

4 19 5
5 20 6
6 21 7
7 23 8
8 24 9
9 25 10
10 27 11
11 28 12
12 29 13
13 31 14
14 32 15
print("Hello world")
starting = 14;
for i in range (7):
    
    if(i %3==0):
        starting=starting+1
    print (i, i+starting, i+1)

Just added if condition to detect刚刚添加了 if 条件来检测

You can do smth like this:你可以这样做:

for i in range(7):
    print(i, i + 15 + i // 3, i + 1)

or, if you want, you can save this delta to variable.或者,如果您愿意,可以将此增量保存到变量中。

inc = 0
for i in range(7):
    if i > 0 and i % 3 == 0:
        inc += 1
    print(i, i + 15 + inc, i + 1)

I think more pythonic way of 2nd variant:我认为第二种变体更pythonic的方式:

inc = 0
for i in range(7):
    if i > 0:
        inc += i % 3 == 0
    print(i, i + 15 + inc, i + 1)

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

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