728x90
โ sort
- ๋ฆฌ์คํธ.sort()
- ๋ฐํ ๊ฐ ์์ด ์ค๋ฆ์ฐจ์(๊ธฐ๋ณธ๊ฐ)์ผ๋ก ์ ๋ ฌ
- ์๋์ ๋ฆฌ์คํธ๊ฐ ์ ๋ ฌ๋ ๊ฐ์ผ๋ก ๋ณํ
array = [5, 2, 4, 3, 1]
array.sort()
print(array) # [1, 2, 3, 4, 5]
โ sorted
- sorted(๋ฆฌ์คํธ)
- ์ค๋ฆ์ฐจ์(๊ธฐ๋ณธ๊ฐ)์ผ๋ก ์ ๋ ฌ๋ ๋ฆฌ์คํธ ๋ฐํ
- ์๋์ ๋ฆฌ์คํธ๋ ๋ณํ X
array = [5, 2, 4, 3, 1]
sorted_array = sorted(array)
print(sorted_array) # [1, 2, 3, 4, 5]
parameter
1. reverse
- ๋ด๋ฆผ์ฐจ์ ์ ๋ ฌ
array.sort(reverse=True) # [5, 4, 3, 2, 1]
sorted_array = sorted(array, reverse=True) # [5, 4, 3, 2, 1]
2. key
- key ๊ฐ์ ๊ธฐ์ค์ผ๋ก ์ ๋ ฌ
- lambda ์ฌ์ฉ
array=[(1, 2), (3, 5), (4, 1), (4, 3), (2, 4)]
array.sort(key=lambda x: x[1]) # [(4, 1), (1, 2), (4, 3), (2, 4), (3, 5)]
sorted_array = sorted(array, key=lambda x: x[1]) # [(4, 1), (1, 2), (4, 3), (2, 4), (3, 5)]
array.sort(key=lambda x: -x[1]) # [(3, 5), (2, 4), (4, 3), (1, 2), (4, 1)]
sorted_array = sorted(array, key=lambda x: -x[1]) # [(3, 5), (2, 4), (4, 3), (1, 2), (4, 1)]
array.sort(key=lambda x:(x[0],x[1])) # [(1, 2), (2, 4), (3, 5), (4, 1), (4, 3)]
sorted_array = sorted(array, key=lambda x:(x[0],x[1])) # [(1, 2), (2, 4), (3, 5), (4, 1), (4, 3)]
728x90