python์์ ์ ๋ ฌํ๊ณ ์ถ์ ๋ ํ์ด์ฌ ๋ด์ฅ ๋ฉ์๋์ `sort()`์ `sorted()`๋ฅผ ํ์ฉํ ์ ์๋ค.
ํ์ด์ฌ ์ ๋ ฌ ๋ฉ์๋
`sort()`๋ listํ ์๋ฃ๊ตฌ์กฐ์๋ง ์ฌ์ฉ๊ฐ๋ฅํ๋ค๋ฉด,
`sorted()`๋ ์๋์ ๊ฐ์ด ๋ฆฌ์คํธํ, ๋ฌธ์ํ, ํํํ๊ณผ ๊ฐ์ ์ดํฐ๋ฌ๋ธํ ์๋ฃ๊ตฌ์กฐ์ ๋ชจ๋ ์ฌ์ฉ ๊ฐ๋ฅํ๋ค.
๋ฆฌ์คํธ sort() ๋ฉ์๋
my_numbers = [2,5,6,1,8,3]
my_numbers.sort()
print(my_numbers) #[1, 2, 3, 5, 6, 8]
sorted() ํจ์
์ ๋ ฌํ๊ณ ์ํ๋ iterable์ ์ฒซ๋ฒ์งธ ์ธ์๋ก ์ ์ด์ค๋ค
list = [5, 4, 3, 2, 1]
print(sorted(list)) #[1, 2, 3, 4, 5]
string = 'abcd'
print(sorted(string)) #['a', 'b', 'c', 'd']
tuple = ('q', 'w', 'e', 'r', 't', 'y')
print(sorted(tuple)) #['e', 'q', 'r', 't', 'w', 'y']
sort() vs. sorted()
sort() | sorted() | |
๋ฌธ๋ฒ | list.sort() | sorted(iterable) |
์๋ณธ ๋ฐ์ดํฐ ๋ณํ ์ฌ๋ถ | O ์๋ณธ ๋ฆฌ์คํธ ๋ณํ |
X ์๋ณธ ์ดํฐ๋ฌ๋ธ ๋ฐ์ดํฐ ๋ถ๋ณ |
๋ฐํ๊ฐ | None | ์๋กญ๊ฒ ์ ๋ ฌ๋ ๋ฆฌ์คํธ |
sort() ์์
list = [1,2,3,1]
print(list.sort()) # None
print(list) # [1, 1, 2, 3]
sorted() ์์
list = [1,2,3,1]
print(sorted(list)) # [1, 1, 2, 3]
print(list) # [1,2,3,1]
์ฐธ๊ณ
https://docs.python.org/ko/3/howto/sorting.html
https://www.geeksforgeeks.org/python-difference-between-sorted-and-sort/?ref=lbp
'Python' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
๊ตฌ๊ธ ์ฝ๋ฉ (0) | 2024.05.28 |
---|---|
๋ฌธ์์ด ์ ๋ ฌ python vs javaScript (0) | 2024.02.18 |