Question:
Write a program to sort the (name, age, height) tuples by ascending order where name is string, age and height are numbers.
1: Sort based on name;
2: Then sort based on age;
3: Then sort by score.
The priority is that name > age > score.
We use itemgetter to enable multiple sort keys.
Program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
from operator import itemgetter, attrgetter l = [] while True: s = raw_input("Enter Details: (Name,Age,Score)[Press Enter to end\n") if not s: break l.append(tuple(s.split(","))) print sorted(l, key=itemgetter(0,1,2)) |
Explanation:
operator
is a built-in module providing a set of convenient operators. In two words operator.itemgetter(n)
constructs a callable that assumes an iterable object (e.g. list, tuple, set) as input, and fetches the n-th element out of it.
Output:
1 2 3 4 5 6 7 8 9 |
Enter Details: (Name,Age,Score)Press Enter to end Lily,19,84 Enter Details: (Name,Age,Score)Press Enter to end Tom,21,67 Enter Details: (Name,Age,Score)Press Enter to end Mark,15,86 Enter Details: (Name,Age,Score)Press Enter to end [('Lily', '19', '84'), ('Mark', '15', '86'), ('Tom', '21', '67')] |
Leave a Reply