๋กœ์ผ“๐Ÿพ
article thumbnail

 

ํŒŒ์ด์ฌ์˜ sort() ํ•จ์ˆ˜๋Š” ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌํ•ด์ฃผ๋Š” ํ•จ์ˆ˜์ž…๋‹ˆ๋‹ค. ๋ฌธ์ž์—ด ๋˜ํ•œ ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌ์ด ๋ฉ๋‹ˆ๋‹ค.

sort(reverse=True) ๋˜๋Š” reverse()๋ฅผ ์ด์šฉํ•˜์—ฌ ๋‚ด๋ฆผ์ฐจ์ˆœ์œผ๋กœ๋„ ๊ตฌํ˜„์ด ๊ฐ€๋Šฅํ•ฉ๋‹ˆ๋‹ค.

 

์ด ๊ธ€์—์„œ๋Š” key ๋งค๊ฐœ๋ณ€์ˆ˜๋ฅผ ๊ฐ€์ง€๋Š” sort()์— ๋Œ€ํ•ด ์•Œ์•„๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค.

 

key ๋งค๊ฐœ๋ณ€์ˆ˜๋ฅผ ๊ฐ€์ง€๋Š” sort() ํ•จ์ˆ˜๋Š” key ๊ฐ’์„ ๊ธฐ์ค€์œผ๋กœ ์ •๋ ฌ๋˜๊ณ  ๊ธฐ๋ณธ๊ฐ’์€ ์˜ค๋ฆ„์ฐจ์ˆœ์ž…๋‹ˆ๋‹ค. ๋˜ํ•œ lambda์‹์„ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

 

๋ฐฑ์ค€ 1181๋ฒˆ ๋ฌธ์ œ๋ฅผ ์˜ˆ์‹œ๋กœ ๋“ค์–ด๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค.

 

 

์ด ๋ฌธ์ œ ๊ฐ™์€ ๊ฒฝ์šฐ sort(key)๋ฅผ ์ด์šฉํ•˜์—ฌ ์‰ฝ๊ฒŒ ๊ตฌํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

 

data_list = ['but','i','wont','hesitate','no','more','no','more','it','cannot','wait','im','yours']

#์ค‘๋ณต ์ œ๊ฑฐ
data_list = list(set(data_list))

data_list.sort()
data_list.sort(key=lambda x : len(x))

print(data_list)

 

์ถœ๋ ฅ ๊ฐ’์— ๋Œ€ํ•ด์„  for ๋ฌธ ๋Œ๋ ค์ฃผ์‹œ๋ฉด ๋ฉ๋‹ˆ๋‹ค.

 

lambda์‹์„ ์ด์šฉํ•˜์—ฌ 2์ฐจ์› ๋ฆฌ์ŠคํŠธ์— ๋Œ€ํ•ด์„œ๋„ ๊ฐ€๋Šฅํ•ฉ๋‹ˆ๋‹ค.

 

data_list = ['but','i','wont','hesitate','no','more','no','more','it','cannot','wait','im','yours']

for index in range(len(data_list)) : 
    data_len = len(data_list[index])
    data_list[index] = (data_list[index], data_len)

data_list.sort(key = lambda x :(x[1], x[0]))
print(data_list)

์ด๋Ÿฐ ์‹์œผ๋กœ๋„ ๋ฌธ์ œ ํ’€์ด๊ฐ€ ๊ฐ€๋Šฅํ•ฉ๋‹ˆ๋‹ค.

 

https://velog.io/@aonee/Python-%EC%A0%95%EB%A0%AC-sort-sorted-reverse

 

profile on loading

Loading...