简体   繁体   中英

How to print elements in list n times

I have a list [0, 4, 1, 2, 3]. I would like to print each element the same number of times as its value, each time on a new row and under each other. Expected output:

[0, 4, 1, 2, 3]
    4  1  2  3
    4     2  3
    4        3
    4

Here is my failed attempt to code. I'm very new to Python, so apologies for what is probably a very rookie question. Hope somebody can help me in the right direction.

list = [0, 4, 1, 2, 3]
print(list)
for x in range(len(list)):
    for y in range(list[x]):
        print(x * " ", end="")
        print(list[x], end="")
    print()

My code gives me this output:

[0, 4, 1, 2, 3]

4 4 4 4
  1
   2   2
    3    3    3

This should do the trick:

my_list = [0, 4, 1, 2, 3]
for i in range(1, len(my_list)):
    for e in my_list:
        if e >= i:
            print(f"{e} ", end="")
        else:
            print("  ", end="")
    print()

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