有没有办法多次重复'A number in the middle of a loop'?

Is there a way to repeat 'A number in the middle of a loop' multiple times?

假设这是我的目标循环,从 10 开始到 6 结束。

for i in range(10,6,-1):
        print(i)

但是我想多次打印8

所以如果循环正在下坡,有没有办法在某个点停止并一次又一次地重复该值 N 次?

非常简单 hard-cording:

for i in range(10,5,-1):
        if i == 8:
            for _ in range(3):
                print(i)
        else:
            print(i)

输出:

10
9
8
8
8
7
6

对于单个循环体的解决方案,

for i in range(10, 5 - 2, -1):
    j= i + min(2, max(0, 8 - i))
    print(j)

您可以将 8 替换为另一个要重复的数字,将 2 替换为另一个重复次数。

你也可以考虑对 while 块做同样的事情 -

loop_range = range(10, 6, -1)
it = iter(loop_range)
while True:
    try:
        item = next(it)
        if item == 8:
            print(*[item]*3, sep='\n')
        print(item)
    except StopIteration:
        break

使用生成器表达式可以使相同的结构更简洁、更易读 -

custom_sequence = ((_,)*3 if _ == 8 else (_,) for _ in range(10, 6, -1))
for i in custom_sequence:
    print(*i, sep='\n')