[英]How do I print a list vertically side by side?
到目前為止,這是我的代碼:
def main():
places=["Hawaii","Ohio","Tokyo","Korea"]
print(places,"\n")
for i in range(0,len(places[0])):
print(places[0][i])
for i in range(0,len(places[1])):
print(places[1][i])
for i in range(0,len(places[2])):
print(places[2][i])
for i in range(0,len(places[3])):
print(places[3][i])
main()
我正在嘗試並排垂直打印4個單詞
向@Ryan喊出建議
from itertools import zip_longest
def main():
for a, b, c, d in zip_longest(*["Hawaii", "Ohio", "Tokyo", "Korea"], fillvalue=" "):
print(a, b, c, d)
main()
輸出:
H O T K
a h o o
w i k r
a o y e
i o a
i
使用嵌套的for循環進行編輯:
def main2():
places = ["Hawaii", "Ohio", "Tokyo", "Korea"]
for i in range(6):
for j in range(4):
try:
print(places[j][i], end=' ')
except:
print(' ', end=' ')
print()
無論您有多少物品,這都是一個通用的解決方案。 可以進行一些優化,該代碼旨在最大程度地簡化代碼。
places=["Hawaii","Ohio","Tokyo","Korea"]
#Find longest word
max_len = max([len(place) for place in places])
# Loop over words and pad them with spaces
for i, place in enumerate(places):
if len(place) < max_len:
places[i] = place.ljust(max_len)
# Print the words one letter at a time.
for i in range(max_len):
print(" ".join([place[i] for place in places]))
您需要這個嗎?
places=["Hawaii","Ohio","Tokyo","Korea"]
vertical_list = [i for place in places for i in list(place)]
for letter in vertical_list:
print(letter)
輸出:
H
a
w
a
i
i
O
h
i
o
T
o
k
y
o
K
o
r
e
a
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.