--When there are multiple related lists, I want to sort the other lists according to the sort order of one list. --Key specification using sorted lambda is often explained in the example of dictionary type data, but note that there are many related data that are not stored in dictionary type.
When there are two arrays like the one below, I want to replace the names according to the sort order of ages.
names = ["Alice", "Bob", "Charlie"]
ages = [10, 30, 20]
It works, but
people = {name: age for name, age in zip(names, ages)}
people = sorted(people.items(), key=lambda x: x[1])
names_sorted = [name for name, _ in people] # ['Alice', 'Charlie', 'Bob']
This method doesn't work if there are people with the same name.
names = ["Alice", "Bob", "Charlie", "Charlie"]
ages = [10, 30, 20, 5]
When using a dictionary, the second Charlie overwrites the first one.
people = {name: age for name, age in zip(names, ages)}
people = sorted(people.items(), key=lambda x: x[1])
names_sorted = [name for name, _ in people] # ['Alice', 'Charlie', 'Bob']
If you try it without making it a dictionary, it will work.
people = [[name, age] for name, age in zip(names, ages)]
people = sorted(people, key=lambda x: x[1])
names_sorted = [name for name, _ in people] # ['Charlie', 'Alice', 'Charlie', 'Bob']
Recommended Posts