IT/Programming

[Python] sorted 함수, sort 메서드 정렬 시 key 함수 활용 용례

nofence 2024. 4. 12. 00:40

 

sorted 함수와 리스트의 sort 메서드 사용 시, 매개변수로 key 함수를 별도로 지정하면 key 함수에서 리턴되는 값을 기준으로 정렬이 적용된다.

>>> sorted(student_tuples, key=lambda student: student[2])
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

>>> sorted(student_tuples, key=lambda student: student[2], reverse=True) 
[('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]

>>> student_tuples = [
...     ('john', 'A', 15),
...     ('jane', 'B', 12),
...     ('dave', 'B', 10),
... ]

>>> student_tuples.sort(key=lambda student: student[2])
>>> student_tuples
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

>>> student_tuples.sort(key=lambda student: student[2], reverse=True) 
>>> student_tuples
[('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]

 

* 참고

Key Functions
Both list.sort() and sorted() have a key parameter to specify a function (or other callable) to be called on each list element prior to making comparisons.

 

The value of the key parameter should be a function (or other callable) that takes a single argument and returns a key to use for sorting purposes. This technique is fast because the key function is called exactly once for each input record.

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