简体   繁体   English

如何垂直并排打印列表?

[英]How do I print a list vertically side by side?

This is my code so far: 到目前为止,这是我的代码:

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()

I'm trying to print the 4 words vertically side by side 我正在尝试并排垂直打印4个单词

Shoutout out to @Ryan for the suggestion 向@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()

Output: 输出:

H O T K
a h o o
w i k r
a o y e
i   o a
i      

Edit with the nested for loops: 使用嵌套的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()

Here's a general solution regardless of how many items you have. 无论您有多少物品,这都是一个通用的解决方案。 Some optimization could be made, this code is intended for maximum clarity. 可以进行一些优化,该代码旨在最大程度地简化代码。

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]))

Do you need this?: 您需要这个吗?

places=["Hawaii","Ohio","Tokyo","Korea"]
vertical_list = [i for place in places for i in list(place)]
for letter in vertical_list:
    print(letter)

Output: 输出:

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.

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