python custom sort

40

python custom sort -

# Works with python 3+
def compare(item):
    #First index (index = 1) used for comparison first -> bigger to smaller -> Descending
    #Second index (index = 2) used for comparison after that -> smaller to bigger -> Ascending
    return (-item[1], item[2])

output = [['perfect', 3, 2], ['just', 1, 10], ['get', 1, 6], ['makes', 1, 1]]
output.sort(key=compare)

>> [['perfect', 3, 2], ['makes', 1, 1], ['get', 1, 6], ['just', 1, 10]]

sorted python lambda -

lst = [('candy','30','100'), ('apple','10','200'), ('baby','20','300')]
lst.sort(key=lambda x:x[1])
print(lst)

python sort a list by a custom order -

# Example usage:
list_to_sort = [('U', 23), ('R', 42), ('L', 17, 'D')]
custom_sort_order = ['R', 'D', 'L', 'U']
sorted(list_to_sort, key=lambda list_to_sort: custom_sort_order.index(list_to_sort[0]))
# Where 0 is the tuple index to use for sorting by custom order
--> [('R', 42), ('L', 17, 'D'), ('U', 23)]

Comments

Submit
0 Comments