【问题标题】:How can I create a nested loop with an increment?如何创建带有增量的嵌套循环?
【发布时间】:2022-08-07 05:32:43
【问题描述】:

我的意思是一个嵌套循环,它将打印出符号。符号的数量应通过增加行来确定。 同时,在移动到下一个数字之前,符号列应该运行一个设定的数字。

结果将如下所示。

@

@

@@

@@

@@@

@@@

等等。

我只设法写了这个:

rows = 5

# Outer loop

symbol = \"@\"

for i in range(rows):

    # Nested loop
    for j in range(i):
        print(symbol, end=\' \')

        print(\'\')
        rows = 5

我试过这个:

rows = 2

# Outer loop

symbol = \"@\"

for i in range(rows):

    # Nested loop

    for j in range(i):

        print(symbol, end=\' \')

        print(\'\')
        rows = 2

我期待像这样的输出:

@

@

@@

@@

@@@

@@@

  • 不会编译在原始发布的表格中。你能让它与实际的源代码相同吗?

标签: python-3.x nested-loops


【解决方案1】:

我想你想要这个:

n = int(input())

for i in range(1,n+1):
    for j in range(1,i+1):
        print("@"*i)

输出:

编辑:

我想你想要尽可能多的 n 重复 @ 所以这是:

n = int(input())

for i in range(1,n+1):
    for j in range(1,n+1):
        print("@"*i)

输出:

这是一个矩阵,你应该玩它。它可能是n*nn*m 表示2 * 22*3 或...

例如这是n+1 * n

n = int(input())

for i in range(1,n+2):
    for j in range(1,n+1):
        print("@"*i)

【讨论】:

  • Parisa.H.R,您的代码与我想要的非常接近。它以我想要的方式工作,除了它以定义数字值的方式打印'@',例如.. 1 =@,2=@@,3=@@@。有没有办法让'@'在移动到下一行之前重复特定值?...例如。我希望它重复 3 次 .. 像单 '@' 将打印 3 次,然后双 '@' 将打印 3 次,依此类推。谢谢
  • @edah,这就像一个矩阵,你应该说你的矩阵是n*mn*n。我从输入中得到 n,在 for 循环中,我创建了那个矩阵。如果你想要一个2*3 矩阵,你需要得到用户的初始输入。但是nested loop 的基础就像我说的那样。
【解决方案2】:

非常感谢,@parisa-h-r。 我从您提供的代码中为外部循环添加了一个单独的输入并且它有效。

n = int(input("This is the row: "))
m = int(input("This is the column: "))
for i in range(n +1):
    for j in range(m):
        print("@"*i)

输出:

【讨论】:

  • 欢迎您,现在您了解如何使用nested for loop 创建矩阵。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-02-10
  • 2018-12-25
  • 2020-05-25
  • 1970-01-01
  • 2021-03-17
  • 2021-12-08
相关资源
最近更新 更多