使用Python垂直翻转ASCII艺术

时间:2014-08-18 23:10:20

标签: python arrays

对于我正在处理的另一个代码,我需要垂直翻转ASCII图像: 我想这样做:

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

进入这个:

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

我现在所拥有的只是将多行输入读入一个数组,但是我如何才能将它打印成最后一个数组和最后一个数组。

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

4 个答案:

答案 0 :(得分:1)

您可以将每行添加到行列表(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)

答案 1 :(得分:1)

这是deque的合理用例 - 您可以将.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')

答案 2 :(得分:1)

您可以使用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)))

答案 3 :(得分:0)

for item in lines[::-1]:
    print item