Question:
You are required to write a program to sort the (name, age, height) tuples by ascending order where the name is a string, age, and height numbers. The tuples are input by the console.
The sort criteria are:
- Sort based on name;
- Then sort based on age;
- Then sort by score.
The priority is that name > age > score.
If the following tuples are given as input to the program:
Tom,19,80
John,20,90
Jony,17,91
Jony,17,93
Json,21,85
Then, the output of the program should be:
[(‘John’, ’20’, ’90’), (‘Jony’, ’17’, ’91’), (‘Jony’, ’17’, ’93’), (‘Json’, ’21’, ’85’), (‘Tom’, ’19’, ’80’)]
Hints:
- In case of input data being supplied to the question, it should be assumed to be a console input.
- We use item getter to enable multiple sort keys.
Solution:
from operator import itemgetter, attrgetter
l = []
while True:
s = raw_input()
if not s:
break
l.append(tuple(s.split(",")))
print sorted(l, key=itemgetter(0,1,2))
Code language: Python (python)