[英]Trying to print vertically in Python
我正在嘗試創建需要垂直打印的圖像:
在for循環中,我可以通過縮進新行來打印出精美的圖像; 但是,我希望圖像逆時針旋轉90度(這是轉置嗎?)。
我試圖from itertools import zip_longest
使用from itertools import zip_longest
但它給出了:
TypeError:zip_longest參數#1必須支持迭代
class Reservoir:
def __init__(self,landscape):
self.landscape = landscape
self.image = ''
for dam in landscape:
self.image += '#'*dam + '\n'
print(self.image)
landscape = [4, 3, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0,
1, 1, 2, 5, 6, 5, 2, 2, 2, 3, 3, 3, 4, 5, 3, 2, 2]
lake = Reservoir(landscape)
print(lake)
我不知道您是否會找到為您執行此操作的函數或庫。 但是您可以手動編碼此旋轉。
您不想在這里顯示真實的圖像,而是打印表示風景的字符。 您必須逐行打印“圖像”,但是由於您的橫向數組代表您希望在每一列中使用的“#”數,因此您必須遍歷想要的總行數以及該行中的每個字符,根據相應的景觀列值打印''或'#'
用
h = max(landscape)
您可以通過查找橫向值的最大值來計算要打印的總行數。
然后,您遍歷這些行
for line in reversed(range(h)):
在該循環中, line
取值為6、5、4等。
對於每一行,您必須遍歷整個格局數組,以確定每一列是否要打印空格或“#”,這取決於格局列( v
)和當前line
for v in self.landscape:
self.image += ' ' if line >= v else '#'
完整程序:
class Reservoir:
def __init__(self, landscape):
self.landscape = landscape
h = max(landscape)
self.image = ''
for line in reversed(range(h)):
for v in self.landscape:
self.image += ' ' if line >= v else '#'
self.image += '\n'
landscape = [4, 3, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 2, 5, 6, 5, 2, 2, 2, 3, 3, 3, 4, 5, 3, 2, 2]
lake = Reservoir(landscape)
print(lake.image)
結果:
#
### #
# ### ##
## ### ######
#### ###############
###### #################
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.