Reputation: 19
I have a list like this:
list = [('Betty', 42.5), ('Andrew', 46.5), ('Zach', 49), ('Cathy',
42.5), ('Jay', 45.5), ('Kevin', 45), ('Cassie', 41), ('Matt', 44),
('Jamie', 44.5), ('Xavier', 45.5), ('Peter', 45.5), ('John', 42.5),
('Jamie', 40.5), ('Joe', 40.5), ('Ellen', 44.5), ('Nancy', 35),
('Jay', 45), ('Bryce', 43.5), ('Gordon', 37), ('Gee', 42.5)]```
How I can sort it by name (if name is same, the one with higher score comes first) in Python?
I tried this but it doesn't sort by score if same name
sorted(list)
Upvotes: 0
Views: 58
Reputation: 4772
it is never good to re-use a name like list
which already has a use in Python, so I changed it to data
. If you negate numbers for sorting purposes, then although 40.5 is less than 44.5, -44.5 is less than -40.5, so if sorting would put the minimum number first, that same sort but on the negation of that numeric field puts the maximum first.
Here is that idea in action:
In [1]: data = [('Betty', 42.5), ('Andrew', 46.5), ('Zach', 49), ('Cathy',
...: 42.5), ('Jay', 45.5), ('Kevin', 45), ('Cassie', 41), ('Matt', 44),
...: ('Jamie', 44.5), ('Xavier', 45.5), ('Peter', 45.5), ('John', 42.5),
...: ('Jamie', 40.5), ('Joe', 40.5), ('Ellen', 44.5), ('Nancy', 35),
...: ('Jay', 45), ('Bryce', 43.5), ('Gordon', 37), ('Gee', 42.5)]
In [2]: sorted(data)
Out[2]:
[('Andrew', 46.5),
('Betty', 42.5),
('Bryce', 43.5),
('Cassie', 41),
('Cathy', 42.5),
('Ellen', 44.5),
('Gee', 42.5),
('Gordon', 37),
('Jamie', 40.5),
('Jamie', 44.5),
('Jay', 45),
('Jay', 45.5),
('Joe', 40.5),
('John', 42.5),
('Kevin', 45),
('Matt', 44),
('Nancy', 35),
('Peter', 45.5),
('Xavier', 45.5),
('Zach', 49)]
In [3]: sorted(data, key=lambda x:(x[0], -x[1]))
Out[3]:
[('Andrew', 46.5),
('Betty', 42.5),
('Bryce', 43.5),
('Cassie', 41),
('Cathy', 42.5),
('Ellen', 44.5),
('Gee', 42.5),
('Gordon', 37),
('Jamie', 44.5),
('Jamie', 40.5),
('Jay', 45.5),
('Jay', 45),
('Joe', 40.5),
('John', 42.5),
('Kevin', 45),
('Matt', 44),
('Nancy', 35),
('Peter', 45.5),
('Xavier', 45.5),
('Zach', 49)]
In [4]:
Jamie and Jay have there maximum number first without needing dual sorts and reversals.
Upvotes: 1
Reputation: 1932
lst = [('Betty', 42.5), ('Andrew', 46.5), ('Zach', 49), ('Cathy', 42.5), ('Jay', 45.5), ('Kevin', 45), ('Cassie', 41), ('Matt', 44), ('Jamie', 44.5), ('Xavier', 45.5), ('Peter', 45.5), ('John', 42.5), ('Jamie', 40.5), ('Joe', 40.5), ('Ellen', 44.5), ('Nancy', 35), ('Jay', 45), ('Bryce', 43.5), ('Gordon', 37), ('Gee', 42.5)]
n0 = sorted(lst, key=lambda x: x[1],reverse=True)
n1 = sorted(n0, key=lambda x: x[0])
print(n1)
Upvotes: 2