简体   繁体   中英

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:

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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