The sorted() function returns a sorted list of the specified iterable object.
You can specify ascending or descending order. Strings are sorted alphabetically, and numbers are sorted numerically.
Note: You cannot sort a list that contains BOTH string values AND numeric values
sorted(iterable, key=key, reverse=reverse)
iterable - Required. The sequence to sort, list, dictionary, tuple etc.key - Optional. A Function to execute to decide the order. Default is Nonereverse - Optional. A Boolean. False will sort ascending, True will sort descending. Default is Falsea = ("b", "g", "a", "d", "f", "c", "h", "e")
x = sorted(a)
print(x)
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
a = (1, 11, 2)
x = sorted(a)
print(x)
[1, 2, 11]
print(sorted(range(1,10), reverse = True))
[9, 8, 7, 6, 5, 4, 3, 2, 1]
a = ("h", "b", "a", "c", "f", "d", "e", "g")
x = sorted(a)
print(x)
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
a = ("h", "b", "a", "c", "f", "d", "e", "g")
x = sorted(a, reverse=True)
print(x)
['h', 'g', 'f', 'e', 'd', 'c', 'b', 'a']
sorted("hello")
["e","h","l","l","o"]
sorted([5,2,1,3,4])
sorted([[2,1,3],[3,2,1],[1,2,3]])
["1","2","3","4","5"]
[[1, 2, 3], [2, 1, 3], [3, 2, 1]]
sorted({3,2,1})
[1,2,3]
sorted({3:1,2:3,1:4})
[1,2,3]
(key가sort됨)
dict = {3: 'b', 2: 'c', 1: 'a'}
print(sorted(dict.items(), key=lambda x: x[1]))
[(1, 'a'), (3, 'b'), (2, 'c')]
value기준으로 정렬되었다.
Reference