I have a list of lists of names and surnames:
[['ARNO', 'ANN'], ['GATES', 'SOPHIA'], ['KERN', 'AMBER'], ['KORN', 'JACOB'], ['STAN', 'EMILY'], ['STAN', 'ANNA'], ['THORENSEN', 'VICTORIA'], ['WAHL', 'ALEXIS']]
I need to sort those with common surnames (ANNA and EMILY STAN) by their names within the given list. How to do it with Python?
CodePudding user response:
You can take advanted of the sorted
method (docs here).
Basically if you want your list sorted by surname first then:
x = [['ARNO', 'ANN'], ['GATES', 'SOPHIA'], ['KERN', 'AMBER'], ['KORN', 'JACOB'], ['STAN', 'EMILY'], ['STAN', 'ANNA'], ['THORENSEN', 'VICTORIA'], ['WAHL', 'ALEXIS']]
sorted_list = sorted(x, key=lambda names: names[1])
if you want to sort by first name then:
x = [['ARNO', 'ANN'], ['GATES', 'SOPHIA'], ['KERN', 'AMBER'], ['KORN', 'JACOB'], ['STAN', 'EMILY'], ['STAN', 'ANNA'], ['THORENSEN', 'VICTORIA'], ['WAHL', 'ALEXIS']]
sorted_list = sorted(x, key=lambda names: names[0])
CodePudding user response:
As the official documentation states, you can set-up sorting by multiple criterias, if your comparison function returns a tuple of multiple values. Hence, you can define your own sorting key, that will return 2 values, like (name, surname)
. This way, name
will be used as a primary sorting criteria, surname
- secondary. Your custom sorting key may look like this:
def custom_key(person: list) -> Tuple[str, str]:
return (person[1], person[0])
# OR
custom_key = lambda person: (person[1], person[0])
It should be used like this:
sorted(people, key=custom_key)
# OR
sorted(people, key=lambda person: (person[1], person[0]))