I have a list
mylist = [['123', 'BOOL', '234'], ['345', 'INT', '456'], ['567', 'DINT', '678']]
I want to sort it with the order of 1. DINT
2. INT
3. BOOL
Result:
[['567', 'DINT', '678'], ['345', 'INT', '456'], ['123', 'BOOL', '234']]
I've seen other similar questions in stackoverflow but nothing similar or easily applicable to me.
Using sort(), lamba, index(): The sort() function does the required in-place sorting(without creating a separate list to store the sorted order) along with a lambda function with a key to specify the function execution for each pair of tuples, the index() function helps to get the order from our custom list list_2.
Python List sort() - Sorts Ascending or Descending List. The list. sort() method sorts the elements of a list in ascending or descending order using the default < comparisons operator between items. Use the key parameter to pass the function name to be used for comparison instead of the default < operator.
A best sorting algorithm in pythonQuicksort is also considered as the ” fastest” sorting algorithm because it has the best performance in the average case for most inputs.
SORT_ORDER = {"DINT": 0, "INT": 1, "BOOL": 2} mylist.sort(key=lambda val: SORT_ORDER[val[1]])
All we are doing here is providing a new element to sort on by returning an integer for each element in the list rather than the whole list. We could use inline ternary expressions, but that would get a bit unwieldy.
Another way could be; set your order in a list:
indx = [2,1,0]
and create a new list with your order wished:
mylist = [mylist[_ind] for _ind in indx] Out[2]: [['567', 'DINT', '678'], ['345', 'INT', '456'], ['123', 'BOOL', '234']]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With