Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

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]]
Comment

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)]
Comment

PREVIOUS NEXT
Code Example
Python :: tkinter simple notification 
Python :: dataclass default list 
Python :: pyplot new figure 
Python :: convert list to dataframe 
Python :: python iterate list 
Python :: get query param in django 
Python :: list of python keywords 
Python :: spam python 
Python :: alpha beta pruning python code 
Python :: finding factorial of a number in python 
Python :: check python version windows 
Python :: python while loop 
Python :: how to write and read dictionary to a file in python 
Python :: remove newline and space characters from start and end of string python 
Python :: merge subplot matplotlib 
Python :: python create directory if non existent 
Python :: How are iloc and loc different? 
Python :: pythob password generator 
Python :: how to add two list by zip function in python 
Python :: how to run terminal commands in python 
Python :: python pipe 
Python :: how to get dictionary input from user in python 
Python :: python how to add up all numbers in a list 
Python :: try except json decode error 
Python :: how to add textbox in pygame window 
Python :: Making a txt file then write 
Python :: python declare a variable 
Python :: can is slice list with list of indices python 
Python :: python print string name in pattern 
Python :: separating tuple in pandas 
ADD CONTENT
Topic
Content
Source link
Name
5+6 =