简体   繁体   中英

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?

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM