ํŒŒ์ด์ฌ ๋”•์…”๋„ˆ๋ฆฌ value ๊ธฐ์ค€ ์ •๋ ฌ (key, lambda)

2020. 11. 22. 17:23ใ†Backend/๐Ÿ Python

1. ๋”•์…”๋„ˆ๋ฆฌ์˜ value๋ฅผ ๊ธฐ์ค€์œผ๋กœ key๋ฅผ ์ •๋ ฌํ•˜๊ธฐ (๋‚ด๋ฆผ์ฐจ์ˆœ ๊ฒฝ์šฐ)

result = {
	1: 2,
	2: 4,
	3: 3,
	4: 6,
	5: 1 }
sorted(result, key = lambda x: result[x], reverse=True)

>>> [4, 2, 3, 1, 5]

 

sorted ๋ฉ”์„œ๋“œ sorted(iterable, key, reverse=) 

  • iterable ํ•  ์ž๋ฃŒํ˜•์„ ๋„ฃ์–ด์ฃผ๊ณ (result),
  • ์ •๋ ฌํ•  ๊ธฐ์ค€์„ ์ •ํ•œ๋‹ค (key = lambda x: result[x])
  • โ–ถ๏ธโ–ถ๏ธโ–ถ๏ธ result[x]๋Š” ๊ฐ key์— ๋Œ€์‘๋˜๋Š” value๋ฅผ ๋œปํ•œ๋‹ค.

 

 

2. 1๋ฒˆ ๊ณผ์ •์—์„œ set์„ ๊ฑฐ์ณ ์ „ํ™˜ํ•˜๊ธฐ

result = sorted(result.items(), key = lambda x: x[1], reverse=True)
>>> [(4, 6), (2, 4), (3, 3), (1, 2), (5, 1)]

print(list(map(lambda x:x[0], result)))
>>> [4, 2, 3, 1, 5]

 

3. operator๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์ •๋ ฌ

import operator

result = {
	1: 2,
	2: 4,
	3: 3,
	4: 6,
	5: 1 }
    
result= sorted(result.items(), key=operator.itemgetter(0))