如何通过 X 数量跳过 for 循环并继续 Y 数量,然后重复

How to skip a for loop by X amount and continue for Y amount, then repeat

为此苦苦挣扎了一段时间,但我如何才能跳过 python 中 X 的循环并继续 Y 然后重复。

例如:

# This loop should loop until 99, but after it reaches a number that is a multiple of 10 e.g. 10,20,30 etc it should continue for 5 iterations, then skip to next multiple of 10.
# E.g 0,1,2,3,4,5,10,11,12,13,14,15,20,21,22,23,24,25,30...etc
for page_num in range(100):
    # Use page_num however

可以在for循环里面直接修改page_num的值,有一定的条件:

for page_num in range(100):
    if str(page_num)[-1]=="6":
        page_num += 4
    print(page_num)

修改循环以使用 10 步,并添加 sub-loop 以使迭代在第 5 个元素后中断。

for j in range(0,100,10):
    for page_num in range(j, j+6):
         # use page_num
x = 4 # How many times to skip
y = 6 # How many times to run

t = [0, True]; x -= 1
for page_num in range(100):
    if t[1] and t[0] < y:
        t[0] += 1
        print(page_num) # What to do after X times next Y times
    elif t[1]:
        t[1] = False
        t[0] = 0

    if not t[1] and t[0] < x:
        t[0] += 1
    elif not t[1]:
        t[1] = True
        t[0] = 0

如果单位位置的数字大于 5,则使用 continue 跳过循环的其余部分。

skip_after = 5
for page_num in range(100):
    if page_num % 10 > skip_after: continue
    # ... Do the rest of your loop 
    print(page_num)

page_num % 10 使用模 % 运算符给出 page_num 除以 10(这是单位位置的数字)的余数。

输出(为了便于阅读而合并成一行):

0 1 2 3 4 5 10 11 12 13 14 15 20 21 22 23 24 25 30

使用itertools.filterfalse

from itertools import filterfalse

for x in (filterfalse(lambda x: (x % 10) > 5, range(0, 100))):
    print(x, end=' ')

输出:

0 1 2 3 4 5 10 11 12 13 14 15 20 21 22 23 24 25 30 31 32 33 34 35 40 41 42 43 44 45 50 51 52 53 54 55 60 61 62 63 64 65 70 71 72 73 74 75 80 81 82 83 84 85 90 91 92 93 94 95 

我会推荐列表理解。如果这是完整的答案,我并不肯定,但我会这样做:

def find_divisors_2(page_num):
    """
    You can insert an algorithmic phrase after if and it will produce the answer.
    """
    find_divisors_2 = [x for x in range(100) if (Insert your algorithm)]
    return find_divisors_2