简体   繁体   中英

sorting by multiple criteria in Python

I'm using Python 3.8. I am trying to sort players by points (in descending order) and then, only if they have the same number of points, by rank.

I've already read Sorting HOW TO , Python sorting by multiple criteria and Sorting by multiple conditions in python .

Here's my code:

from operator import itemgetter

players_results = [
    ("Pierre", 1.0, 1),
    ("Matthieu", 1.0, 2),
    ("Joseph", 0.5, 3),
    ("Marie", 0.0, 4),
    ("Michel", 0.5, 5),
    ("Raphael", 0.0, 6),
]

sorted_by_points = sorted(players_results, key=itemgetter(1), reverse=True)
points_descending_rank_ascending = sorted(sorted_by_points, key=itemgetter(2))
print(points_descending_rank_ascending)

# [('Pierre', 1.0, 1), ('Matthieu', 1.0, 2), ('Joseph', 0.5, 3), ('Marie', 0.0, 4), ('Michel', 0.5, 5), ('Raphael', 0.0, 6)]

In each tuple, the number of points are of float type while the rank is of integer type. My problem is that Michel should be before Marie, but that's not the case. Can someone explain what I have to implement differently?

One solution could be:

sorted(players_results, key=lambda x:(-x[1],x[2]))

OUTPUT

[('Pierre', 1.0, 1), ('Matthieu', 1.0, 2), ('Joseph', 0.5, 3), ('Michel', 0.5, 5), ('Marie', 0.0, 4), ('Raphael', 0.0, 6)]

I suggest using 3rd party libraries, such as pandas:

import pandas as pd

players_results = [
    ("Pierre", 1.0, 1),
    ("Matthieu", 1.0, 2),
    ("Joseph", 0.5, 3),
    ("Marie", 0.0, 4),
    ("Michel", 0.5, 5),
    ("Raphael", 0.0, 6),
]
df = pd.DataFrame(players_results)
df.columns = ["name", "points", "rank"]
df.sort_values(["points", "rank", "name"], ascending=[False, True, True])

结果

Attemping to respect your script, something like this works:

if __name__ == '__main__':

    players_results = [
        ("Pierre", 1.0, 1),
        ("Matthieu", 1.0, 2),
        ("Joseph", 0.5, 3),
        ("Marie", 0.0, 4),
        ("Michel", 0.5, 5),
        ("Raphael", 0.0, 6),
    ]


    # In one line:
    points_descending_rank_ascending = sorted(players_results, key=lambda t: (-t[1], t[2]))
    print(points_descending_rank_ascending)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM