Reputation: 45
I have this piece of code that converts two lists into vertical columns and prints them:
team1 = ['Vàlentine', 'Consus', 'Never Casual ', 'NucIear', 'Daltwon']
team2 = ['The Aviator', 'Iley', 'Nisquick', 'Dragoon', 'WAACK']
for t1, t2 in zip(team1, team2):
print('%-20s %s' % (t1, t2))
How can this code be adjusted to add a third list say team3 = ['...']
?
Output:
Vàlentine The Aviator <team3 here>
Consus Iley
Never Casual Nisquick
NucIear Dragoon
Daltwon WAACK
Using:
for t1, t2, t3 in zip(team1, team2, team3):
print('%-20s %s' % str(t1, t2, t3))
Does not seem to work.
Upvotes: 1
Views: 59
Reputation: 71610
Or try an one-liner:
print('\n'.join(map('%-20s %-20s %s'.__mod__, zip(team1, team2, team3))))
Also, unlike @SUNGJIN's answer, they're all processed and printed once, so you can easily save it into a variable:
mystring = '\n'.join(map('%-20s %-20s %s'.__mod__, zip(team1, team2, team3)))
Upvotes: 1
Reputation: 61617
Since you said "multiple" rather than "three" in the subject heading, let's get fully general about it.
To generalize the code, we would want to start with a list of lists:
columns = [
['Vàlentine', 'Consus', 'Never Casual ', 'NucIear', 'Daltwon'] # team 1
['The Aviator', 'Iley', 'Nisquick', 'Dragoon', 'WAACK'] # team 2
]
To get "rows" consisting of one element from each contained "column" list, we still use zip
, but we need the *
operator to pass an arbitrary number of parameters to it; and then since we're trying to be general about how many elements are in the column, we can't unpack it into separate variables. So:
for row in zip(*columns):
Then we need a formatting operation that can handle however many elements in a row. We can do this by formatting each element in its own 20-wide string (it is recommended to use new-style string formatting), and passing them all - again using the *
operator - to print
. The neatest way to do this is with a generator expression, thus:
print(*(f'{name:<20}' for name in row))
Upvotes: 0
Reputation: 126
Like this
team1 = ['Vàlentine', 'Consus', 'Never Casual ', 'NucIear', 'Daltwon']
team2 = ['The Aviator', 'Iley', 'Nisquick', 'Dragoon', 'WAACK']
team3 = ['Ronaldo', 'Messi', 'Zidane', 'Me', 'Raul']
for t1, t2, t3 in zip(team1, team2, team3):
print('%-20s %-20s %s' % (t1, t2, t3))
Upvotes: 5