TIL - sorted() function

Seob·2020년 7월 7일
0

TIL

목록 보기
5/36
post-thumbnail

Definition and Usage

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

Syntax

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 None
  • reverse - Optional. A Boolean. False will sort ascending, True will sort descending. Default is False

sort a tuple

a = ("b", "g", "a", "d", "f", "c", "h", "e")
x = sorted(a)
print(x)

['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']

sort nuberic

a = (1, 11, 2)
x = sorted(a)
print(x)

[1, 2, 11]

sort range

print(sorted(range(1,10), reverse = True))

[9, 8, 7, 6, 5, 4, 3, 2, 1]

sort ascending

a = ("h", "b", "a", "c", "f", "d", "e", "g")
x = sorted(a)
print(x)

['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']

sort descending

a = ("h", "b", "a", "c", "f", "d", "e", "g")
x = sorted(a, reverse=True)
print(x)

['h', 'g', 'f', 'e', 'd', 'c', 'b', 'a']

sort string

sorted("hello")

["e","h","l","l","o"]

sort list

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

sort set

sorted({3,2,1})

[1,2,3]

sort dict

sorted({3:1,2:3,1:4})

[1,2,3]
(keysort 됨)

sort value of a dictionary

dict = {3: 'b', 2: 'c', 1: 'a'}
print(sorted(dict.items(), key=lambda x: x[1]))

[(1, 'a'), (3, 'b'), (2, 'c')]
value기준으로 정렬되었다.

Reference

profile
Hello, world!

0개의 댓글