简体   繁体   English

如何反转python中的for循环并从左到右打印元素

[英]how to reverse the for loop in python and print the elements from left to right

This is my code which i wrote in python这是我用python编写的代码

n = 5
row = 2 * n - 2
for i in range(n,-1,-1):
    for j in range(row):
        print(end="")

    row -=2

    for k in range(i+1):
        print('*',end=" ")

    print()

The output what is get is this得到的输出是这个

* * * * *  
* * * * 
* * * 
* * 
*

i want to print this start from left to right order for example例如,我想从左到右打印这个开始

The expected output is :-预期的输出是:-

* * * * *
  * * * *
    * * *
      * *
        *

if it's any possible way to print the elements from left to right because in most of my program i need that logic i'm searching for it please help me and even i used reversed function for loop it will reverse the loop but i'm not getting what i expect如果有任何可能的方式从左到右打印元素,因为在我的大多数程序中我需要那个逻辑我正在寻找它请帮助我,即使我使用了反向函数循环它也会反向循环但我不是得到我的期望

n = 5
print(*[' '.join(' '*i + '*'*(n-i)) for i in range(n)], sep='\n')

Output:输出:

* * * * *
  * * * *
    * * *
      * *
        *

Explanation:解释:

for i in range(n):
    chars = ' '*i + '*'*(n-i)  #  creating list of (i) spaces followed
                                   #  by (n-i) stars to finish a line of n elements
    print(' '.join(chars))  # join prepared values with spaces

Here is a simple solution not using list comprehension:这是一个不使用列表理解的简单解决方案:

n = 5
for i in range(n+1):
    for j in range(i):
        print("  ", end="")
    for j in range(i+1, n+1):
        print("* ", end="")
    print()

Output:输出:

* * * * * 
  * * * * 
    * * * 
      * * 
        *

My solution - I'm new to python as well:我的解决方案 - 我也是 python 新手:

n = 5
c = 0
for i in range(n, 0, -1):
    print(" " * c + "*" * i)
    c += 1

or或者

n = 5
c = 0
while n >= 0:
    print(" " * c + "*" * n)
    n -= 1
    c += 1

The problem is that print itself cannot print right-justified text.问题是print本身无法打印右对齐的文本。 But you can print a right-justified string instead of using multiple calls to print .但是您可以打印一个右对齐的字符串,而不是使用多次调用print

Here's your original code, using join instead of an inner loop:这是您的原始代码,使用join而不是内部循环:

n = 5
row = 2 * n - 2
for i in range(n,-1,-1):
    for j in range(row):
        print(end="")

    row -=2

    row_str = " ".join(["*"] * i)
    print(row_str)

And here's the modified code to make the output right-justified:这是使输出右对齐的修改代码:

n = 5
row = 2 * n - 2
whole = row + 1
for i in range(n,-1,-1):
    for j in range(row):
        print(end="")

    row -=2

    row_str = " ".join(["*"] * i).rjust(whole)
    print(row_str)

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

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