2017-11-21 2 views
1

Dies ist mein Code so weit:Wie drucke ich eine Liste vertikal nebeneinander?

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

Ich versuche, die 4 Wörter vertikal nebeneinander

+0

Sie werden wahrscheinlich wollen schließlich, dies zu tun mit [ 'zip_longest'] (https://docs.python.org/3/library/itertools.html#itertools.zip_longest) – Ryan

Antwort

1

Haben Sie diese

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 ?: müssen drucken:

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

Shoutout zu @Ryan für den Vorschlag

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

Ausgang:

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

Bearbeiten mit der verschachtelten for-Schleifen:

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

@LeoEvans glücklich Hausaufgaben – AK47

2

Hier ist eine allgemeine Lösung, unabhängig davon, wie viele Elemente, die Sie haben. Einige Optimierungen könnten gemacht werden, dieser Code ist für maximale Klarheit gedacht.

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