늒네 기록

[python] list.sort(), 혹은 sorted()에서의 key에 대하여 본문

언어 공부 기록/python

[python] list.sort(), 혹은 sorted()에서의 key에 대하여

jaeha lee 2020. 10. 16. 21:04

docs.python.org/3/howto/sorting.html

 

Sorting HOW TO — Python 3.9.0 documentation

Sorting HOW TO Author Andrew Dalke and Raymond Hettinger Release 0.1 Python lists have a built-in list.sort() method that modifies the list in-place. There is also a sorted() built-in function that builds a new sorted list from an iterable. In this documen

docs.python.org

위 페이지에서 'key functions'의 내용을 정리한다.

1
2
print(sorted("This is a test string from Andrew".split(), key=str.lower))
# ['a', 'Andrew', 'from', 'is', 'string', 'test', 'This']
cs

문서에 위와 같은 예시가 나오는데, 간단히 뜯어보면

- "This is a test string from Andrew"라는 string이 주어져있다.

- 이걸 split()한다. split()은 변수로 받은 문자열을 기준으로 주어진 string을 잘라서 list로 만들어주는데, 아무 변수도 안 넘기면 기본적으로 공백 문자를 기본으로 잘라준다.

- 즉, split()된 결과물은 ['This', 'is', 'a', 'test', 'string', 'from', 'Andrew']가 된다.

- 그리고 이걸 sort하면 ['Andrew', 'This', 'a', 'from', 'is', 'string', 'test']가 된다. 대문자가 아스키코드상 더 작은 값을 가지기 때문에, 대문자로 시작하는 단어들이 더 앞에 나온다.

 

그런데 단어들을 대문자 상관 없이 sort하고 싶다면..? 먼저 단어에 나온 대문자들을 전부 소문자로 바꾸고, 그 다음 이 소문자 단어들을 key로 잡아서 sort한 다음, 기존의 단어들을 결과물로 취하면 좋겠다. 대략 아래와 같은 과정을 거치면 된다.

1
2
3
4
5
6
7
8
9
= 'This is a test string from Andrew'
= s.split()
# ['This', 'is', 'a', 'test', 'string', 'from', 'Andrew']
= [(str.lower(x), x) for x in s]
# [('this', 'This'), ('is', 'is'), ('a', 'a'), ('test', 'test'), ('string', 'string'), ('from', 'from'), ('andrew', 'Andrew')]
s.sort()
# [('a', 'a'), ('andrew', 'Andrew'), ('from', 'from'), ('is', 'is'), ('string', 'string'), ('test', 'test'), ('this', 'This')]
= [x[1for x in s]
# ['a', 'Andrew', 'from', 'is', 'string', 'test', 'This']
cs

이 과정을 짧게 줄여주는 것이 바로 처음의 예시 코드에 있던 'key' 변수다. 의미 그대로, 저 key 변수로 넘겨주는 함수를 각 아이템에 씌워놓은 값을 기준 삼아 sort를 하겠다는 것.

 

그렇기 때문에 첫 예시에서는 key값에 str.lower 함수 그 자체를 넘겨주었고, 비슷하게 key를 만들어낼 수 있는 함수를 적당히 넣어주면 잘 작동할 것이다. 그래서 key로 딱 한 번만 쓰고 버릴 람다 함수를 넘겨주는 경우도 자주 볼 수 있다. 람다 함수에 대해서는 아래의 포스트를 참조하자.

2020/10/01 - [언어 공부 기록/python] - [python] lambda와 reduce의 활용을 통한 리스트 아이템의 곱 구하기

반응형
Comments