Take these two list of strings for example.
names = ['Jack', 'Steve', 'Marc', 'Xavier', 'Bob']
names_copy = ['Steve', 'Marc', 'Xavier', 'Bob', 'Jack']
Essentially I'm trying to find a way to sort names_copy in the same way that names is sorted.
So, a sorted version of names_copy would result in ['Jack', 'Steve', 'Marc', 'Xavier', 'Bob']
NOTE: in my program, names_copy is being created with a map, so I cannot use
.sort(),sorted()works however.
I understand the sorted() function takes in a key parameter indicating the sort order, but I'm not too sure how to use it here.
CodePudding user response:
The easiest way would be to do:
names_copy_sorted = sorted(names_copy, key=names.index)
This assumes that every item in names_copy is actually an item in names. But this solution isn't very efficient. It would be more efficient to create a dictionary that assigns a priority to the items from names and then uses those priorities as key. For example:
priorities = dict((n, i) for i, n in enumerate(names))
names_copy_sorted = sorted(names_copy, key=priorities.get)
If there are items in names_copy that aren't in names then you could adjust that with something like:
priorities = dict((n, i) for i, n in enumerate(names))
default = len(priorities)
def key(name): return priorities.get(name, default)
names_copy_sorted = sorted(names_copy, key=key)
This way the items in names_copy that are not in names are pushed to the back.
Be aware that duplicates in names are dealt with differently: names.index uses the first occurrence as priority, while the priorities.get version uses the last.
CodePudding user response:
- First we have a List that contains duplicates:
- Create a dictionary, using the List items as keys. This will automatically remove any duplicates because dictionaries cannot have duplicate keys.
- Then, convert the dictionary back into a list: Now we have a List without any duplicates, and it has the same order as the original List.
I hope this helps.
