如何并排垂直打印列表?

问题描述 投票:1回答:3

到目前为止这是我的代码:

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个单词

python python-3.x list loops python-2.x
3个回答
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()

2
投票

无论您拥有多少物品,这都是一般解决方案。可以进行一些优化,该代码旨在最大限度地提高清晰度。

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

1
投票

你需要这个吗?:

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
© www.soinside.com 2019 - 2024. All rights reserved.