python - 数半金字塔 Python

标签 python nested-loops

我正在尝试在 python 中打印一个在左侧呈星形的半金字塔。 到目前为止,这是我的代码

for i in range(1,12):
    for j in range(12 - i):
        print(" ", end = " ")
    for j in range(1, i):
        print(j, end = " " )
    print("\n")

我的输出是

                    1 

                  1 2 

                1 2 3 

              1 2 3 4 

            1 2 3 4 5 

          1 2 3 4 5 6 

        1 2 3 4 5 6 7 

      1 2 3 4 5 6 7 8 

    1 2 3 4 5 6 7 8 9 

  1 2 3 4 5 6 7 8 9 10 

但是,我的输出应该是相反的顺序:

            1

          2 1

        3 2 1

      4 3 2 1

    5 4 3 2 1

我怎样才能做出这个改变?

最佳答案

只需反转第二个循环——打印实际数字的循环:

for j in range(i-1, 0, -1):

最后一个参数控制“步长”,即变量在每次循环迭代中的变化量。输出:

                1 

              2 1 

            3 2 1 

          4 3 2 1 

        5 4 3 2 1 
        ...

关于python - 数半金字塔 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42497164/

相关文章:

R 内存管理 - 增加内存消耗

c - c中的While循环递增

python - 修复 Python 中的 4 个嵌套 for 循环

python - 在 Excel 中删除 Pandas 条件格式

python - 使用 selenium 和 python 抓取 Instagram 关注者页面

python - 如何在python中声明变量类型,C风格

python - Twisted ProcessProtocol 读取 channel

python - TypeError : argument 1 must be string or read-only character buffer, 不是无

docker - Ansible:遍历库存组

swift - 解决 Swift 3 中过多的 else-if 语句