Reputation: 356
I'm trying to output the values of 2 lists side by side using list comprehension. I have an example below that shows what I'm trying to accomplish. Is this possible?
code:
#example lists, the real lists will either have less or more values
a = ['a', 'b', 'c,']
b = ['1', '0', '0']
str = ('``` \n'
'results: \n\n'
'options votes \n'
#this line is the part I need help with: list comprehension for the 2 lists to output the values as shown below
'```')
print(str)
#what I want it to look like:
'''
results:
options votes
a 1
b 0
c 0
'''
Upvotes: 14
Views: 55633
Reputation: 1
a = ['a', 'b', 'c']
b = ['1', '0', '0']
print("options" + '\t' + votes")
for i in range(len(a)):
print(a[i] + '\t ' + b[i])
Upvotes: 0
Reputation: 1
This code will work for variable lengths of lists too:
a = ['aaaaaaa', 'b', 'c']
b = ['1', '000000000000', '0', '2']
max_a = max(len(x) for x in a)
max_b = max(len(y) for y in b)
if len(a)>len(b):
new_b = b + [' ']*(len(a)-len(b))
for i in range(len(a)):
print(f"{a[i]:{max_a}}|{new_b[i]:{max_b}}")
else:
new_a = a + [' ']*(len(b)-len(a))
for j in range(len(b)):
print(f"{new_a[j]:{max_a}}|{b[j]:{max_b}}")
Output:
aaaaaaa|1
b |000000000000
c |0
|2
Upvotes: 0
Reputation: 643
[print(x,y) for x,y in zip(list1, list2)]
Note the square brackets enclosing the print statement.
Upvotes: 0
Reputation: 1275
from __future__ import print_function # if using Python 2
a = ['a', 'b', 'c']
b = ['1', '0', '0']
print("""results:
options\tvotes""")
for x, y in zip(a, b):
print(x, y, sep='\t\t')
Upvotes: 4
Reputation: 6149
You can use the zip()
function to join lists together.
a = ['a', 'b', 'c']
b = ['1', '0', '0']
res = "\n".join("{} {}".format(x, y) for x, y in zip(a, b))
The zip()
function will iterate tuples with the corresponding elements from each of the lists, which you can then format as Michael Butscher suggested in the comments.
Finally, just join()
them together with newlines and you have the string you want.
print(res)
a 1
b 0
c 0
Upvotes: 20
Reputation: 5708
This works:
a = ['a', 'b', 'c']
b = ['1', '0', '0']
print("options votes")
for i in range(len(a)):
print(a[i] + '\t ' + b[i])
Outputs:
options votes
a 1
b 0
c 0
Upvotes: 8