Carstairs
Carstairs

Reputation: 63

Python - Output Elements in Two Lists on Separate Lines

I am trying to figure out how I would print each element in both lists on seperate lines like:

Chapter One Test [large space] 84%

but instead, it prints the whole list out like:

['Chapter One Test', 'Chapter Two Test', 'Chapter Three Test'] [84%, 75%, 90%]

Does anyone know how to fix this issue?

Upvotes: 1

Views: 206

Answers (3)

dawg
dawg

Reputation: 103834

Given:

>>> li1=['Chapter One Test', 'Chapter Two Test', 'Chapter Three Test']
>>> li2=['84%', '75%', '90%']

You can zip the two lists together:

>>> print('\n'.join(['{}\t{}'.format(*t) for t in zip(li1,li2)]))
Chapter One Test    84%
Chapter Two Test    75%
Chapter Three Test  90%

If you want to make a table, you might make the field widths fixed rather than \t separated:

>>> print('\n'.join(['{:22s}{:3s}'.format(*t) for t in zip(li1,li2)]))
Chapter One Test      84%
Chapter Two Test      75%
Chapter Three Test    90%

Read more about format mini-language to find out more about those options.

Upvotes: 1

vash_the_stampede
vash_the_stampede

Reputation: 4606

Sticking with your current approach you could make small adjustments by either printing the index's one by one or making a loop using the index from one of the enumerated lists since they have equal length and sorted to match already, I would also say look into l.just and r.just to achieve formatting that lines up nicely

print ("{}                     {}".format(testSet[0], calculatedMarks[0]))
print ("{}                     {}".format(testSet[1], calculatedMarks[1]))
print ("{}                     {}".format(testSet[2], calculatedMarks[2]))

for idx, item in enumerate(testSet):
    print("{}                      {}".format(testSet[idx], calculatedMarks[idx]))

Upvotes: 0

ctj232
ctj232

Reputation: 390

You could try:

   for test, grade in zip(testSet, calculatedMarks):
       print("{}    {}".format(test, grade))

Your example would print the entire lists in a single print call.

This will iterate over the lists (creating pairs from each list using zip) and print each pair on it's own line.

As in Dawg's answer, you can use a list comprehension and the str.join function instead of a for loop with a body to get this in a single line/print statement.

Upvotes: 1

Related Questions