APZ
APZ

Reputation: 17

How to create a table from a list of tuples?

I have two lists:

students = ['A', 'B', 'C']
marks = [45, 78, 12]

I need to sort the students list based on the marks and display the output in a specific manner.

students = ['student1', 'student2', 'student3']
marks = [45, 78, 12]  #, 14, 48,]
sortedlist = sorted(zip(marks, students), reverse=True)
print(sortedlist)

I am getting the output as:

[(78, 'student2'), (45, 'student1'), (12, 'student3')]

I want the output as:

a 2D table with first column student and the second column marks

Is it possible to achieve? Also in the output, I need only two highest numbers and not all elements in the zipped list.

Upvotes: 0

Views: 181

Answers (1)

Tomerikoo
Tomerikoo

Reputation: 19440

Simply format the printing but only for the n=2 first elements:

for mark, name in sortedlist[:n]:
    print(name, '\t', mark)

# one-liner: print('\n'.join(name + '\t' + str(mark) for mark, name in sortedlist[:n]))

And this prints:

student2    78
student1    45

Upvotes: 1

Related Questions