Is there a way to make my own sort list?
like I want to sort this :
['planets', 'animals', 'humans']
['animals', 'planets', 'humans']
['humans', 'planets', 'animals']
to
['humans', 'animals', 'planets']
['humans', 'animals', 'planets']
['humans', 'animals', 'planets']
CodePudding user response:
Pass a key
function to sort
or sorted
that maps the list elements into something that has the order you want. Here's one possible solution for the example you gave:
>>> def kitaro(s):
... return len(s), s
...
>>> sorted(['planets', 'animals', 'humans'], key=kitaro)
['humans', 'animals', 'planets']
>>> sorted(['animals', 'planets', 'humans'], key=kitaro)
['humans', 'animals', 'planets']
>>> sorted(['humans', 'planets', 'animals'], key=kitaro)
['humans', 'animals', 'planets']
Another possibility:
>>> def kitaro(s):
... return {s: i for i, s in enumerate(
... ['humans', 'animals', 'planets']
... )}.get(s)
...
>>> sorted(['planets', 'animals', 'humans'], key=kitaro)
['humans', 'animals', 'planets']
CodePudding user response:
I've had to do something similar. Place each item into a list with the preferred order:
ordering_list = ['humans', 'planets', 'animals']
Translate this list into a dict of item versus priority
ordering_dict = {item: i for i, item in enumerate(ordering_list)}
Define a method to use as the sort key. For unknown values we can choose len(ordering_dict)
to place these items at the back. You could also use any arbitrary value depending on your needs.
def ordering_key(item):
return ordering_dict.get(item, len(ordering_dict))
Now sorting is easy:
import pprint
unsorted_data = [
['planets', 'animals', 'humans'],
['animals', 'planets', 'humans'],
['humans', 'planets', 'animals'],
['foo', 'planets', 'animals', 'humans'],
]
sorted_data = [
sorted(data, key=ordering_key) for data in unsorted_data
]
pprint.pprint(sorted_data)
[['humans', 'planets', 'animals'],
['humans', 'planets', 'animals'],
['humans', 'planets', 'animals'],
['humans', 'planets', 'animals', 'foo']]