简体   繁体   English

在范围内循环时跳过第n个值-python

[英]skip every nth value when looping over a range - python

Let's say I have something like this. 假设我有这样的事情。

for i in range((n**2)+(n-1)):
    print i,

Here 这里

n = any integer after one(2, 3, 4 etc.)

Now, if n is 2 , I'll get values of i as 0, 1, 2, 3, 4 . 现在,如果n is 2 ,我将得到i 0, 1, 2, 3, 4

What I need is to be able to skip every nth value of i so that, if n is 2 , my output will be 0, 1, 3, 4 and if n = 3 , my output will be 0, 1, 2, 4, 5, 6, 8, 9, 10 我需要能够跳过i每第n个值,以便如果n is 2 ,则我的输出将为0, 1, 3, 4如果n = 3 ,则我的输出将为0, 1, 2, 4, 5, 6, 8, 9, 10

Thank you. 谢谢。

One such way to do that is just skip the iterations of the loop you don't want to iterate with a continue statement 一种这样的方式是只跳过不想用continue语句迭代的循环迭代

for i in range(0,11):
    if i % 3 == 0 and i != 0:
        continue
    print(i)


1
2
4
5
7
8
10

Based on what Brian Cain said, I have found the solution for my question. 根据Brian Cain所说的,我找到了解决我问题的方法。 Thanks Brian. 谢谢布莱恩。 The following is the code I was looking for: 以下是我正在寻找的代码:

for i in range ((n**2)+(n-1)):
    if (i+1) % (n+1) == 0 and i != 0:
        continue
    print i

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

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