简体   繁体   English

python for循环打印下降范围的多行

[英]python for loop to print multiple lines of a descending range

To get an output like 获得类似的输出

0 1 2 3 4 5 6 7 8 9 
  0 1 2 3 4 5 6 7 8 
    0 1 2 3 4 5 6 7
      0 1 2 3 4 5 6
        0 1 2 3 4 5
          0 1 2 3 4 
            0 1 2 3 
              0 1 2
                0 1
                  0

How would I go about it? 我将如何处理? I'm going off something like 我要去的东西像

for y in range(10):
    print
    i = ?
    for x in range(i):
        print x,
        i = i - 1

to update the range, but I'm not sure how to write it. 更新范围,但我不确定如何编写。

OR should I keep range the same and somehow replace each integer with a space? 还是应该保持范围相同,并以某种方式用空格替换每个整数?

Print the whitespaces before printing the numbers in each line: 在打印每行中的数字之前,请打印空白:

for y in range(10):
    print
    i = 10 - y
    print ' ' * (y * 2),  # whitespaces
    for x in range(i):
        print x,
        i = i - 1

You can right align the output using str.format, allowing for the range and the spaces and decrementing the inner loop by -i each iteration: 您可以使用str.format右对齐输出,允许范围和空格,并在每次迭代时通过-i减少内部循环:

for i in xrange(10):
    print("{:>19}".format(" ".join(map(str, xrange(10-i)))))

Output: 输出:

0 1 2 3 4 5 6 7 8 9
  0 1 2 3 4 5 6 7 8
    0 1 2 3 4 5 6 7
      0 1 2 3 4 5 6
        0 1 2 3 4 5
          0 1 2 3 4
            0 1 2 3
              0 1 2
                0 1
                  0

If you want it to work for any n you need to know how long the longest string will be: 如果您希望它对任何n都起作用,则需要知道最长的字符串将持续多长时间:

spaces = len(" ".join(map(str, xrange(n))))
for i in xrange(n):
    print("{:>{spaces}}".format(" ".join(map(str, xrange(n-i))), spaces=spaces))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM