본문 바로가기
Python/Python

lambda, sorted()

by Sondho 2020. 5. 13.

lambda

  • lambda 인자 : 표현식
  • 함수를 한 줄로 표현할 수 있음
# 예제1

## x+y를 구하는 함수
def sum(x, y):
    return x+y 
print(sum(5, 10))

## lambda를 사용하여 x+y를 구현
(lambda x,y: x + y)(10, 20)


# 실행결과
15
# 예제2

## x**2를 구하는 함수
def power(x):
    return x**2
print(list(map(power, range(5))))

## lambda를 사용해 x**2를 구현
print(list(map(lambda x: x**2, range(5))))


# 실행결과
[0, 1, 4, 9, 16]

참고 : https://wikidocs.net/64

 

위키독스

온라인 책을 제작 공유하는 플랫폼 서비스

wikidocs.net

 


 

sorted()

sorted(문자열/리스트/딕셔너리 등 정렬할 내용 , key 매개 변수)

 

key 매개 변수의 값은 단일 인자를 취하고 정렬 목적으로 사용할 키를 반환하는 함수여야 합니다.

# 예제1

menu_price = [
    ('hotdog', 1500),
    ('jjajang', 4500),
    ('jjambbong', 5000),
]
print(sorted(menu_price, key=lambda price: price[1])) # lambda로 구해진 price를 매개변수로 sorted


# 실행결과
[('hotdog', 1500), ('jjajang', 4500), ('jjambbong', 5000)]
# 예제2

print(sorted("This is a test string from Andrew".split(), key=str.lower)) # 소문자로 변환된 str을 매개변수로 sorted
print(sorted("This is a test string from Andrew".split()))


# 실행결과
['a', 'Andrew', 'from', 'is', 'string', 'test', 'This'] # 대문자 소문자 관계없이 알파벳순으로 정렬
['Andrew', 'This', 'a', 'from', 'is', 'string', 'test']
# 예제3

## key=word.find를 매개변수로 word를 sorted 했을 때,
## 입력한 word와 일치하면 그룹단어
result = 0
for i in range(int(input())):
    word = input()
    print(f"list({word}) = {list(word)}")
    print(f"sorted({word}) = {sorted(word)}") # 위치 상관없이 알파벳 오름차순 정리
    print(f"sorted({word}, key=word.find) = {sorted(word, key=word.find)}") # 기존 위치로 알파벳 오름차순 정리
    if list(word) == sorted(word): 
        result += 1
    print()
print(result)


# 실행결과
3
happy
list(happy) = ['h', 'a', 'p', 'p', 'y']
sorted(happy) = ['a', 'h', 'p', 'p', 'y']

new
list(new) = ['n', 'e', 'w']
sorted(new) = ['e', 'n', 'w']
sorted(new, key=word.find) = ['n', 'e', 'w']

abcabc
list(abcabc) = ['a', 'b', 'c', 'a', 'b', 'c']
sorted(abcabc) = ['a', 'a', 'b', 'b', 'c', 'c']
sorted(abcabc, key=word.find) = ['a', 'a', 'b', 'b', 'c', 'c']

 

 

참고 : https://docs.python.org/ko/3/howto/sorting.html

 

정렬 HOW TO — Python 3.8.3rc1 문서

정렬 HOW TO 저자 Andrew Dalke와 Raymond Hettinger 배포 0.1 파이썬 리스트에는 리스트를 제자리에서(in-place) 수정하는 내장 list.sort() 메서드가 있습니다. 또한, 이터러블로부터 새로운 정렬된 리스트를 만

docs.python.org

 

댓글