[英]How to print elements in list n times
I have a list [0, 4, 1, 2, 3].我有一个列表 [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.
我对 Python 非常陌生,因此对于可能是一个非常菜鸟的问题,我深表歉意。 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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.