I want to order a List with elements like this:
a = ['A1', 'A2', 'A11', 'A12', 'A3', 'B1', 'B12', 'EC21', 'EC1']
If I do
a.sort()
The output is
['A1', 'A11', 'A12', 'A2', 'A3', 'B1', 'B12', 'EC1', 'EC21']
While the ideal output is
['A1', 'A2', 'A3', 'A11', 'A12', 'B1', 'B12', 'EC1', 'EC21']
Any ideas?
CodePudding user response:
The problem here is that by default you are sorting strings and therefore the sorting you show in your example is indeed correct from a computational standpoint.
On the other hand, the result you want to obtain expects to ignore the prefix (in your example "A"), consider the rest as integers and apply the sorting on that part.
A possible solution can be written using Python's sort key parameter:
def my_function(e):
return int(e.split('A')[1])
a = ['A1', 'A2', 'A11', 'A12', 'A3']
a.sort(key=my_function)
Output:
['A1', 'A2', 'A3', 'A11', 'A12']
If your prefix can be different from "A" you can use a RegEx in order to accomodate all the cases, please let me know if that is a requirement so I can adjust my example.
You can read more about the topic in Python official documentation here but I will copy the relevant part also in this answer for simplicity:
The value of the key parameter should be a function (or other callable) that takes a single argument and returns a key to use for sorting purposes. This technique is fast because the key function is called exactly once for each input record.
CodePudding user response:
a.sort(key=len)
Here, we have added the parameter key, which means that the function is applied to each list item and then sorted. So the list is also sorted based on the length of each element.