Python Forum

Full Version: Sort on basis of (name,age,score)
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
You are required to write a program to sort the (name, age, height) tuples by ascending order where name is string, age and height are numbers. The tuples are input by console. The sort criteria is:
1: Sort based on name;
2: Then sort based on age;
3: 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')]

I'm stuck on this and have no idea how to start. Any help would be appreciated
Try
sorted(List of tuples)
Quote:I'm stuck on this and have no idea how to start. Any help would be appreciated
Make a serious effort, then post your code.
We are glad to help, but will not write it for you.
(May-12-2020, 06:23 PM)Larz60+ Wrote: [ -> ]Make a serious effort, then post your code.
Here you go. Also, i forgot to mention the hint -
Quote:In case of input data being supplied to the question, it should be assumed to be a console input.
We use itemgetter to enable multiple sort keys.
from operator import itemgetter
list1 = []
while True:
    input_list = input()
    if not input_list:
        break
    list1.append(tuple(input_list.split(",")))

print(sorted(list1, key=itemgetter(0,1,2)))
Quote:
print(sorted(list1, key=itemgetter(0,1,2)))

Could be written as:

print(sorted(list1))
sort does also compare the elements in sequences.
It's allowed to have different data-types per field, but they must be the same over the whole list.
L = [(1, "a"), (1, "A")]

print(sorted(L))
Output:
[(1, 'A'), (1, 'a')]
Without the use of key, sort compares the whole element (1, 'A') with (1, "a").
The ASCII character A has the value 65 and a is 97.
The default order is from small > big. Sort compares the first value, then the second and so far.
If you don't have to exclude values from the tuple, the use of key is not necessary.
@DeaD_EyE, even if I use
print(sorted(list1))
it gives the same output
Output:
[('(Tom', '19', '80)', '(John', '20', '80)', '(Jony', '17', '91)', '(Jony', '17', '93)', '(Json', '21', '85)')]
Drop the quotes you have around each tuple
As DeaD_EyE already pointed out - watch out string comparisons. Current dataset is carefully selected.

If age is provided as string then:

>>> '9' < '29'
False
Your problem is where you have the quotes in the string -
inlist = [('Tom',19,80),('John',20,90),('Jony',17,91),('Jony',17,93),('Json',21,85)]
print(sorted(inlist))
Output:
[('John', 20, 90), ('Jony', 17, 91), ('Jony', 17, 93), ('Json', 21, 85), ('Tom', 19, 80)]
Thanks for all your replies, I was finally able to solve the code