Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

list sort by key python

>>> student_tuples = [
...     ('john', 'A', 15),
...     ('jane', 'B', 12),
...     ('dave', 'B', 10),
... ]
>>> sorted(student_tuples, key=lambda student: student[2])   
# sort by age
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
Comment

sort list by key

# sort list by key
st1 = [ [ 1, 2], [3, 4], [4, 2], [ -1, 3], [ 4, 5], [2, 3]]
st1.sort()
print(st1)					# sort by  1st element [ [ -1, 3 ], [ 1, 2 ], [ 2, 3 ] ...
st1.sort(reverse=True)
print(st1)					# sort decending [ [ 4, 5 ], [ 3, 4], [ 2, 3 ] ...
st1.sort(key=lambda x: x[1])			# sort by 2nd element accending
print(st1)					# [ [ 1, 2 ], [ 4, 2 ], [ -1, 3 ] ...
st1.sort(key=lambda x: x[0] + x[1])		# sort by sum of 1st and 2nd element accending
print(st1)					# [ [ -1, 3 ], [ 1, 2 ], [ 2, 3 ] ...
# lambda undefined function
def sort_func(x) :				# classic way
	return x[0] + x[1]
st1.sort(key=sort_func)
st1.sort(key=lambda x: x[0] + x[1])		# defined function lambda at place

Comment

python sort array by key

# sort list by key
st1 = [ [ 1, 2], [3, 4], [4, 2], [ -1, 3], [ 4, 5], [2, 3]]
st1.sort()
print(st1)					# sort by  1st element [ [ -1, 3 ], [ 1, 2 ], [ 2, 3 ] ...
st1.sort(reverse=True)
print(st1)					# sort decending [ [ 4, 5 ], [ 3, 4], [ 2, 3 ] ...
st1.sort(key=lambda x: x[1])			# sort by 2nd element accending
print(st1)					# [ [ 1, 2 ], [ 4, 2 ], [ -1, 3 ] ...
st1.sort(key=lambda x: x[0] + x[1])		# sort by sum of 1st and 2nd element accending
print(st1)					# [ [ -1, 3 ], [ 1, 2 ], [ 2, 3 ] ...
# lambda undefined function
def sort_func(x) :				# classic way
	return x[0] + x[1]
st1.sort(key=sort_func)
st1.sort(key=lambda x: x[0] + x[1])		# defined function lambda at place
Comment

PREVIOUS NEXT
Code Example
Python :: add rectangle to image python 
Python :: append multiple elements python 
Python :: how to remove a specific element from an array in python 
Python :: python label 
Python :: break 
Python :: list arguments of function python 
Python :: remove list of value from list python 
Python :: Adding new column to existing DataFrame in Pandas 
Python :: ros python service client 
Python :: graph outlier detection 
Python :: flask socketio send 
Python :: stdin and stdout in python 
Python :: validate 
Python :: python3 create list from string 
Python :: join tables pandas 
Python :: list inside a list in python 
Python :: export an excel table to image with python 
Python :: python get all numbers between two numbers 
Python :: add key to dictionairy 
Python :: search an array in python 
Python :: reference variable python 
Python :: new line 
Python :: python else syntax 
Python :: Math Module floor() Function in python 
Python :: a int and float python 
Python :: how to check if a string value is nan in python 
Python :: python3 password generator script 
Python :: print statements 
Python :: camp cretaceous.com 
Python :: to text pandas 
ADD CONTENT
Topic
Content
Source link
Name
4+2 =