“Python Custom Sort” Kode Jawaban

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]]
Dream Shift

Diurutkan Python Lambda

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

Python Urutkan daftar berdasarkan pesanan khusus

# 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)]
Charles-Alexandre Roy

Jawaban yang mirip dengan “Python Custom Sort”

Pertanyaan yang mirip dengan “Python Custom Sort”

Lebih banyak jawaban terkait untuk “Python Custom Sort” di Python

Jelajahi jawaban kode populer menurut bahasa

Jelajahi bahasa kode lainnya