python 15장. 람다(lambda)

Hyuna·2024년 8월 4일

Python 기본

목록 보기
15/17
post-thumbnail

  • 람다 표현식은 식 형태로 되어있다
  • 람다 표현식은 함수를 간편하게 작성할 수 있어 다른 함수 인수로 넣어 사용하게 된다



1. 람다(lambda)


lambda arguments: expression


f = lambda x: x+10
print(f(1))
>> 11
✔ lambda: 람다 함수 정의 키워드
✔ arguments: 함수의 입력 인자,콤마로 구분
✔ expression: 인자를 사용하는 표현식, 표현식 결과가 함수의 반환값

def mult_table(n):
    return lambda x:x*n
    
n = int(input('Enter a number: '))    
y = mult_table(n)   # y = x: x*n
print(f'The entered number is {n}, which is a perfect number.')

for i in range(11):
    print(('%d x %d = %d' %(n, i, y(i))))  # x= 1 2 3 4 6 7 8 9 10

  • 변수에 할당하지 않고 직접 호출 가능

print((lambda x: x*3.14)(12))

>> 37.68

print((lambda x: x-3.14)(12))

>> 8.86
  • 변수가 여러 개 필요한 경우 바깥에 선언해주는 것이 좋다
y = 10
print((lambda(x: x+y)(1))

>>11

2. map(func,iterables)

  • 주어진 함수를 iterable 각 요소에 반복하여 적용
  • func: 각 요소에 적용할 함수
  • iterables: 함수를 적용할 데이터 집합
#예제1
print(list(map(lambda x: x + 10, [1,2,3])))

>> [11, 12, 13]

#예제2
my_pets = ['alfred', 'tabitha', 'william', 'arla']
	
uppered_pets = list(map(str.upper,my_pets))
print(uppered_pets)

>> ['ALFRED', 'TABITHA', 'WILLIAM', 'ARLA']

#예제3
input_string = "This is a sample string"

# 공백을 기준으로 문자열을 나누고 리스트 형태로 반환
result = list(map(str, input_string.split()))

print(result)

>> ['This', 'is', 'a', 'sample', 'string']
  • 2개 요소 람다 없이 함수로 인자처리
def add(x,y):
    return x+y

num1 = [1, 2, 3, 4, 5]
num2 = [10, 20, 30 , 40, 50]
add_num = map(add,num1,num2)

print(list(add_num))


>> [11, 22, 33, 44, 55]
  • map에 여러 객체 넣기

a =[1,2,3,4,5]
b=[2,4,6,8,10]

d = list(map(lambda x,y: x*y,a,b))
print(d)
# 람다식은 x*y까지

>> [2, 8, 18, 32, 50]

✔ 조건식 사용하기

* if만 사용시 문법 에러

lambda 매개변쉬 식1 if 조건식 else2

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(list(map(lambda x: str(x) if x % 3== 0 else x, a)))

>> [1, 2, '3', 4, 5, '6', 7, 8, '9', 10]
* 람다 표현식 안에서 elif 사용 불가
* if문만 연속사용
* 복잡하지 않은 조건식인데 알아보기 힘든 경우 def 함수로 표현하는 것이 낫다
a = [1,2,3,4,5,6,7,8,9,10]
d = list(map(lambda x: str(x) if x ==1 else float(x) if x ==2 else x + 10,a ))
print(d)

>> ['1', 2.0, 13, 14, 15, 16, 17, 18, 19, 20]
💡 아래의 문제를 map과 lambda식으로 바꿔보자

def checkNum(x):
      if x < 3:
            return x
      elif x < 6:
            return x * 2
      else:
            return x * 3

numbers = [2,3,4,5,6,7]
result = map(checkNum, numbers)
print(list(result))

*****

numbers = [2,3,4,5,6,7]

result = map(lambda x: x if x<3 else x*2 if x<6  else x*3, numbers)
print(list(result))



>> [2, 6, 8, 10, 18, 21]

3. filter

  • 함수가 참 또는 거짓 반환하도록 요청
  • 논리에 거짓인 요소를 필터링 하여 제거
filter(func, iterable)
* 하나의 iterable만 필요(map은 여러 iterable 가능)

#예제1
def f(x):
    return x > 5 and x <10

a = [8,3,2,10,15,7,1,9,0,11]
d = list(filter(f,a))
print(d)

>> [8, 7, 9]


#예제2
dromes = ("구로구", "rewire", "madam", "freer", "마그마", "kiosk")
palindromes = list(filter(lambda word: word == word[::-1], dromes))
print(palindromes)

>> ['구로구', 'madam', '마그마']

4. reduce

#functools 모듈에서 reduce 함수를 가져옴
from functools import reduce
reduce(func, iterable[,initial])
  • 함수(func): 두 개 인자를 하나의 값으로 결합
  • 시퀀스(iterable): 누적 적용될 시퀀스
  • 초기값(initial): 선택적으로 제공할 수 있는 초기값
#예제1
def f(x,y):
    return x+y
a= [1,2,3,4,5]
from functools import reduce
print(reduce(f,a))

>> 15

#예제2
from functools import reduce
numbers = [3, 4, 6, 9, 34, 12]
def custom_sum(first, second):
    return first + second
result = reduce(custom_sum, numbers, 10) #초기값 10 + 리스트(i) 요소
print(result)


>> 78


#예제3
a= [1, 2, 3, 4, 5]
from functools import reduce
d = reduce(lambda x,y: x+y,a)
print(d)

>> 15



💡 주어진 사람들의 리스트를 사람의 나이에 따라 정렬하자

>> 람다 함수를 사용하여 정렬
people = [
{"name": "John", "age": 45},
{"name": "Diana", "age": 32},
{"name": "Tom", "age": 20}
]

sorted_peole = sorted(people, key=lambda x: x['age'])

print(sorted_peole)

📍sort/sorted 📍
* sort: 원본 리스트를 직접 정렬
* sorted: 원본 리스트를 변경하지 않고, 졍렬된 새로운 리스트 반환
#sort는 단독 사용
numbers.sort(reverse=True)
print("내림차순 정렬: ", numbers)



#sorted는 변수 선언 후 사용
numbers_reverse = sorted(numbers, reverse=True)
print("내림차순 정렬: ", numbers_reverse)


💡 주어진 숫자 리스트에서 최대값을 찾자

>> reduce와 람다 사용
from functools import reduce

num = [5, 8, 6, 10, 9, 2]

max_num = reduce(lambda x,y: x if x>y else y,num)
print(max_num)


💡 문자열 리스트에서 각 문자열의 첫 글자만 대문자로 변한해보자

>> map과 람다 사용
words = ["hello", "world", "python", "programming"]

cap_words = list(map(lambda word: word.capitalize(),words))
print(cap_words)


💡 주어진 제품 리스트에서 가격이 100보다 크고, 재고가 10개 이상인 제품만 추출해보자

>> filter과 람다 사용
products = [
{"name": "Product A", "price": 150, "stock": 5},
{"name": "Product B", "price": 120, "stock": 12},
{"name": "Product C", "price": 50, "stock": 20},
{"name": "Product D", "price": 200, "stock": 9}
]

filtered_products = list(filter(lambda p: p['price'] > 100 and p['stock'] >=
10, products))

print(filtered_products) 


💡 주어진 딕셔너리를 값 기준으로 오름차순으로 정렬하는 람다 함수를 작성해보자

>> data = {'apple': 5, 'banana': 2, 'orange': 8, 'kiwi': 3}
data = {'apple': 5, 'banana': 2, 'orange': 8, 'kiwi': 3}

result = sorted(data.items(), key = lambda item:item[1] )
print(result)




*****
#함수식 표현

def get_value(item):
    return item[1]

def sorted_items(data):
    items = data.items()
    sorted_items = sorted(items, key = get_value)
    return dict(sorted_items)

data = {'apple': 5, 'banana': 2, 'orange': 8, 'kiwi': 3}

result = sorted_items(data)
print(result)



💡 최대공약수를 구하는 함수를 작성하고 이를 이용해 리스트에 있는 여러 숫자의 최대공약수를 구해보자

>> numbers = [48, 64, 16, 32]
# reduce만 사용
import math
from functools import reduce

def get_gcd(numbers):
    return reduce(math.gcd, numbers)


numbers = [48, 64, 16, 32]
result = get_gcd(numbers)
print('최대공약수: ', result)

# reduce, lambda 사용

from functools import reduce

def get_gcd(a, b):
    while b:
        a, b = b, a % b
    return a

numbers = [48, 64, 16, 32]
result = reduce(lambda x, y: get_gcd(x, y), numbers)
print('최대공약수:', result)

0개의 댓글