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 list by custom function

from functools import cmp_to_key
sorted(mylist, key=cmp_to_key(compare))
Comment

python sort list by custom function

from functools import cmp_to_key
sorted(mylist, key=cmp_to_key(lambda item1, item2: fitness(item1) - fitness(item2)))
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 :: rotatelist in python 
Python :: iterating over lines in a file 
Python :: django reverse lazy 
Python :: python tkinter scrollbar 
Python :: do i need do some set when i use GPU to train tensorflow model 
Python :: List Nested Lists 
Python :: read list of dictionaries from file python 
Python :: parce que in english 
Python :: infinite for loop in python 
Python :: calculate sum in 2d list python 
Python :: count true in a dataframe 
Python :: ajouter dans une liste python 
Python :: python for print 
Python :: non blocking socket python 
Python :: python range function examples 
Python :: na in python 
Python :: how to separate date and time in python 
Python :: python infinite loop 
Python :: renamecolumns pandas 
Python :: opencv write video 
Python :: shebang line python 
Python :: restricting user access to web pages 
Python :: add border to table in python pptx 
Python :: bassie en adriaan 
Python :: max(X_train, key=len).split() 
Python :: RuntimeError: cannot open featureclass in python 
Shell :: Pyperclip could not find a copy/paste mechanism for your system 
Shell :: uninstall node js in ubunt 
Shell :: installing zoom on ubuntu 20.04 
Shell :: mvn clean install skip tests 
ADD CONTENT
Topic
Content
Source link
Name
3+3 =