Algorithm/๐Ÿ“š Concept

[์•Œ๊ณ ๋ฆฌ์ฆ˜] ๊ธฐ์ค€์— ๋”ฐ๋ผ ์ •๋ ฌ(sort/sorted) - ํŒŒ์ด์ฌ(Python)

J1Yun 2021. 8. 29. 17:11
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