簡體   English   中英

使用Python垂直翻轉ASCII藝術

[英]Vertically flip ASCII art with Python

對於我正在處理的另一個代碼,我需要垂直翻轉ASCII圖像:我要這樣做:

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

到這個:

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

我現在所要做的就是將多行輸入讀取到一個數組中,但是我該如何使它最后打印第一個數組,然后首先打印底部數組。

text = ""
stopword = ""
while True:
    line = input()
    if line.strip() == stopword:
        break

您可以將每行添加到行列表( list.append ),然后在打印之前反轉該列表( list[::-1] ):

lines = []
stopword = ""
while True:
    line = input()
    if line.strip() == stopword:
        break
    lines.append(line) # Add to the list of lines
for line in lines[::-1]: # [::-1] inverts the list
    print(line)

這是deque的合理用例-您可以將.extendleft與任何可迭代.extendleft一起使用。

from collections import deque

stop_word = '' # an empty line causes a stop
lines_until_stop = iter(input, stopword)
d = deque()
d.extendleft(lines_until_stop)
print(*d, sep='\n')

您可以通過使用reversed反轉所有行來簡化所有操作。

>>> art = '''
...      *
...     ***
...    *****
...     ***
...     ***
... '''
>>> print('\n'.join(reversed(art.splitlines())))
    ***
    ***
   *****
    ***
     *

我今天很慷慨,因此舉一個完整的例子:

text = ""
stopword = "END"
lines = []
while True:
    line = input()
    if line.strip() == stopword:
        break
    lines.append(line)

print('\n'.join(reversed(lines)))
for item in lines[::-1]:
    print item

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM