์ƒˆ์†Œ์‹

๐Ÿ ํŒŒ์ด์ฌ (Python)

ํŒŒ์ด์ฌ (Python) - (์ •๋ ฌ ์ด์ •๋ฆฌ) sort( ), sorted( ) , ํŠน์ • key๋ฅผ ๊ธฐ์ค€์œผ๋กœ ์ •๋ ฌํ•˜๊ธฐ ,์ด์ค‘ ๋ฆฌ์ŠคํŠธ ์ •๋ ฌ , ๋‹ค์ค‘ ์กฐ๊ฑด ์ •๋ ฌ

  • -

sorted()

 

Prototype

sorted( <list> , key = <function> , reverse = <bool>)
# <list> ๋ฟ ์•„๋‹ˆ๋ผ, <Tuple>, <Dictionary>, <Str>์—๋„ ์‚ฌ์šฉ ๊ฐ€๋Šฅํ•˜๋‹ค.
  • ์›๋ณธ ๋‚ด์šฉ์„ ๋ฐ”๊พธ์ง€ ์•Š๊ณ , ์ •๋ ฌํ•œ ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•œ๋‹ค.
  • List, tuple, Dictionary, str์— ๋ชจ๋‘ ์‚ฌ์šฉ ๊ฐ€๋Šฅํ•˜๋‹ค.
  • key ๋ฅผ ํ†ตํ•˜์—ฌ ์ •๋ ฌํ•  ๊ธฐ์ค€์„ ์ •ํ•  ์ˆ˜ ์žˆ๋‹ค.
  • reverse ๊ฐ€ True์ด๋ฉด ๋‚ด๋ฆผ์ฐจ์ˆœ, False์ด๋ฉด ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌ๋œ๋‹ค.

 

arr = [10, 40, 20, 15]
arr = sorted(arr, reverse = True)
print(arr)

>>>> [40, 20, 15, 10]

sort()

 

Prototype

<list>.sort(key = <function>, reverse = <bool>)
  • ์›๋ณธ ์ž์ฒด๋ฅผ ์ˆ˜์ •ํ•œ๋‹ค.
  • ๋ฐ˜ํ™˜๊ฐ’์€ None
  • Tuple , Dictionary, Str ์—๋Š” ์‚ฌ์šฉ์ด ๋ถˆ๊ฐ€ํ•˜๋‹ค.

key๊ฐ’์„ ์‚ฌ์šฉํ•˜๋ฉด ์—ฌ๋Ÿฌ๊ฐ€์ง€ ๊ธฐ์ค€์œผ๋กœ ์ •๋ ฌ์„ ์‹คํ–‰ํ•  ์ˆ˜ ์žˆ๋‹ค.

 

2์ค‘ ๋ฆฌ์ŠคํŠธ์—์„œ ์ •๋ ฌํ•˜๊ธฐ

array = [[50, "apple"], [30, "banana"] , [400, "melon"]]

์œ„์™€ ๊ฐ™์ด [Int, Str]ํ˜•์‹์˜ ์š”์†Œ๋ฅผ ๊ฐ€์ง„ ๋ฆฌ์ŠคํŠธ๊ฐ€ ์กด์žฌํ• ๋•Œ

 

Int ๋ฅผ ๊ธฐ์ค€์œผ๋กœ ์ •๋ ฌํ•˜๊ธฐ

.sort() ํ•จ์ˆ˜ ์‚ฌ์šฉ

array.sort(key = lambda x:x[0])
print(array)
>>>>> [[30, 'banana'], [50, 'apple'], [400, 'melon']]

sorted() ํ•จ์ˆ˜ ์‚ฌ์šฉ

print(sorted(array, key = lambda x: x[0]))
>>>>> [[30, 'banana'], [50, 'apple'], [400, 'melon']]

 

 

Str์„ ๊ธฐ์ค€์œผ๋กœ ์ •๋ ฌํ•˜๊ธฐ

Sort() ํ•จ์ˆ˜ ์‚ฌ์šฉ

array.sort(key = lambda x:x[1])
print(array)
>>>>>[[50, 'apple'], [30, 'banana'], [400, 'melon']]

sorted() ํ•จ์ˆ˜ ์‚ฌ์šฉ

print(sorted(array, key = lambda x: x[1]))
>>>>>[[50, 'apple'], [30, 'banana'], [400, 'melon']]

 

 

 

#  key๊ฐ€ ์—ฌ๋Ÿฌ๊ฐœ ์ผ๋•Œ (๋‹ค์ค‘์กฐ๊ฑด ์ •๋ ฌ)

 

array = [("A", 18, 300000) , ("F", 24, 10000), ("T", 24, 200000),("Q",24,5000000), ("B", 70, 5000)]
# (<์ด๋ฆ„> , <๋‚˜์ด> , <์žฌ์‚ฐ>) ์ด๋ผ๊ณ  ํ•˜๋ฉด
  • ์œ„์˜ ๋ฆฌ์ŠคํŠธ์ฒ˜๋Ÿผ ์ •๋ ฌํ•ด์•ผ ํ• ๋•Œ ๊ณ ๋ คํ•ด์•ผ ๋งŽ์€ ๊ฒฝ์šฐ๊ฐ€ ์žˆ์„๋•Œ๋Š” ํŠœํ”Œํ˜•์‹์œผ๋กœ key = lambda x: (x[0] , x[2]) lambda์‹์„ ์„ธ์›Œ์ฃผ๋ฉด ๋œ๋‹ค.
  • ๊ทธ๋ฆฌ๊ณ  ๋‚ด๋ฆผ์ฐจ์ˆœ์œผ๋กœ ํ•˜๊ณ  ์‹ถ๋‹ค๋ฉด ๋งˆ์ด๋„ˆ์Šค ๋ถ€ํ˜ธ๋ฅผ ๋ถ™์—ฌ์ฃผ๋ฉด ๋œ๋‹ค. key= lambda x: (-x[0], x[2])

 

 

๋‚˜์ด๋ฅผ ๊ธฐ์ค€์œผ๋กœ ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌํ•˜๊ณ  , ๊ฐ™์€ ๋‚˜์ด๋ผ๋ฉด ์žฌ์‚ฐ์„ ๋‚ด๋ฆผ์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌ

array.sort(key = lambda (x: x[1], -x[2]))
print(array)

>>> [('A', 18, 300000), ('Q', 24, 5000000), ('T', 24, 200000), ('F', 24, 10000), ('B', 70, 5000)]
Contents

ํฌ์ŠคํŒ… ์ฃผ์†Œ๋ฅผ ๋ณต์‚ฌํ–ˆ์Šต๋‹ˆ๋‹ค

์ด ๊ธ€์ด ๋„์›€์ด ๋˜์—ˆ๋‹ค๋ฉด ๊ณต๊ฐ ๋ถ€ํƒ๋“œ๋ฆฝ๋‹ˆ๋‹ค.