[Memo] Python3 list sort

About sorting lists in Python 3

Simple list sorting

list = [1,3,2,4]
list.sort()
print(list)
# [1, 2, 3, 4]

Or use the sorted () function

list = [1,3,2,4]
print(sorted(list))
# [1, 2, 3, 4]
descending order
list = [1,3,2,4]
list.sort(reverse=True)
print(list)
# [4, 3, 2, 1]

Dictionary type sort

dict = {"a","c","d","b"}
print(sorted(dict))
# ['a', 'b', 'c', 'd']

Sort dictionary in list (Key specified)

list_dict = [{"no":1,"name":"Devit"},{"no":4,"name":"Josh"},{"no":2,"name":"Sam"},{"no":3,"name":"Tom"}]
print(sorted(list_dict,key=lambda x:x["no"]))
# [{'name': 'Devit', 'no': 1}, {'name': 'Sam', 'no': 2}, {'name': 'Tom', 'no': 3}, {'name': 'Josh', 'no': 4}]
#descending order
print(sorted(list_dict,key=lambda x:x["no"],reverse=True))
# [{'name': 'Josh', 'no': 4}, {'name': 'Tom', 'no': 3}, {'name': 'Sam', 'no': 2}, {'name': 'Devit', 'no': 1}]


Recommended Posts

[Memo] Python3 list sort
Python3 List / dictionary memo
Python memo
python memo
Python memo
[Python] Sort
python memo
Python # sort
Python memo
[Python] list
Python memo
Python memo
[Python] Memo dictionary
python beginner memo (9.1)
★ Memo ★ Python Iroha
[Python] EDA memo
Python 3 operator memo
Python> Comprehension / Comprehension> List comprehension
[My memo] python
Python3 metaclass memo
[Python] Basemap memo
Python beginner memo (2)
Python list manipulation
[Python] Numpy memo
Python numbers, strings, list types (Python learning memo ①)
Sorted list in Python
Python Exercise 2 --List Comprehension
List of python modules
Python> list> extend () or + =
Python class (Python learning memo ⑦)
My python environment memo
python openCV installation (memo)
Python module (Python learning memo ④)
[Python] Sort the list of pathlib.Path in natural sort
Visualization memo by Python
Bubble sort in Python
Python list comprehension speed
Python self-made class sort
Python test package memo
python unittest assertXXX list
A memo about writing merge sort in Python
python regular expression memo
Binary search (python2.7) memo
[My memo] python -v / python -V
Python Tips (my memo)
[Python] Memo about errors
OpenCV3 Python API list
Python error list (Japanese)
DynamoDB Script Memo (Python)
Python sort cheat sheet
List find in Python
Python basic memo --Part 2
python recipe book Memo
Basic Python command memo
List operation memo writing
Python OpenCV tutorial memo
Custom sort in Python3
[Python] Sort collection types
Python basic grammar memo
TensorFlow API memo (Python)
Sort list elements in a specified order in Python