如何使用嵌套循环在 Python 中获取此模式?

问题描述 投票:0回答:2

1
2 3
4 5 6
7 8 9 10

for r in range (1,5):
    for c in range (0,r):
        print(r+c, end = " ")
    print()

但是,这返回输出为:
1
2 3
3 4 5
4 5 6 7

请让我知道如何让序列不每次都重复前一行的最后一位数字......

python nested-loops
2个回答
1
投票

您可以在循环中使用计数器,例如:

v = 1  # initialise counter
for i in range(1, 5):
    for j in range(i):
        print(f"{v}", end=" ")
        v += 1  # increment counter
    print()

0
投票
current = 1
counter = 0
for x in range(0, 5):
    l = ""
    for y in range(current, current + x):
        counter += 1
        l = l + str(counter) + " "
    print(l)

这使得

1 
2 3 
4 5 6 
7 8 9 10 
© www.soinside.com 2019 - 2024. All rights reserved.