KT AIVLE/Python Syntax

lambda, filter, reduce

bestone888 2024. 10. 6. 22:28

lambda, filter, reduce 함수

1. lambda [매개변수] : (표현식)

In [4]:
# lambda 이용한 덧셈
add = lambda x, y : x + y
add(100,200)
Out[4]:
300

1-1. key 매개변수로 사용되는 lambda

1. sorted()에서 key 매개변수

In [7]:
# 단어 길이 순서대로 정렬
words = ['apple', 'banana', 'cherry', 'date']
sorted_words = sorted(words, key = lambda word : len(word))
sorted_words
Out[7]:
['date', 'apple', 'banana', 'cherry']
In [8]:
# 사전의 특정 키 값을 기준으로 정렬

people = [
    {'name': 'Alice', 'age': 30, 'height': 165},
    {'name': 'Bob', 'age': 25, 'height': 180},
    {'name': 'Charlie', 'age': 35, 'height': 170}
]

# 나이 기준 오름차순 정렬
sorted_by_age = sorted(people, key = lambda person: person['age'])
sorted_by_age
Out[8]:
[{'name': 'Bob', 'age': 25, 'height': 180},
 {'name': 'Alice', 'age': 30, 'height': 165},
 {'name': 'Charlie', 'age': 35, 'height': 170}]
In [9]:
# 키를 기준으로 내림차순 정렬
sorted_by_height = sorted(people, key = lambda person: person['height'], reverse = True)
sorted_by_height
Out[9]:
[{'name': 'Bob', 'age': 25, 'height': 180},
 {'name': 'Charlie', 'age': 35, 'height': 170},
 {'name': 'Alice', 'age': 30, 'height': 165}]

2. min(), max()에서 key

In [11]:
# 가장 긴 단어 찾기
words = ['apple', 'banana', 'cherry', 'date']
longest_word = max(words, key = lambda word: len(word))
longest_word
Out[11]:
'banana'
In [12]:
# 가장 짧은 단어 찾기
shortest_word = min(words, key = lambda word: len(word))
shortest_word
Out[12]:
'date'
In [13]:
# 학생 성적에 따른 정렬
students = [
    ('John', 85),
    ('Jane', 92),
    ('Dave', 89),
    ('Anna', 95)
]

# 성적 기준으로 오름차순 정렬
sorted_by_score = sorted(students, key = lambda student: student[1])
sorted_by_score
Out[13]:
[('John', 85), ('Dave', 89), ('Jane', 92), ('Anna', 95)]
In [14]:
# 성적 기준으로 내림차순 정렬
sorted_by_score_desc = sorted(students, key = lambda student: student[1], reverse = True)
sorted_by_score_desc
Out[14]:
[('Anna', 95), ('Jane', 92), ('Dave', 89), ('John', 85)]
In [ ]:
 

2. filter(적용시킬_함수, {반복가능 객체})

In [16]:
# adult_func()함수와 필터 함수의 사용
def adult_func(n):
    if n >= 19:
        return True
    else:
        return False


ages = [34, 29, 20, 18, 13, 54]
for age in filter(adult_func, ages):
    print(age, end = ' ')
34 29 20 54 
In [17]:
# lambda 함수 & filter 함수
ages = [34, 29, 20, 18, 13, 54]
for age in filter(lambda x: x >= 19, ages):
    print(age, end = ' ')
34 29 20 54 
In [18]:
# 음수 추출
def minus(n):
    if n <0:
        return True
    else:
        return False

nlist = [-30, 45,-5, -90, 20, 53, 77, -36]
for num in filter(minus, nlist):
    print(num, end = ' ')
-30 -5 -90 -36 
In [19]:
# lambda 함수 이용한 음수 추출
nlist = [-30, 45,-5, -90, 20, 53, 77, -36]
for num in filter(lambda x: x<0, nlist):
    print(num, end = ' ')
-30 -5 -90 -36 
In [20]:
# lambda 함수 + map()
nlist = [1,2,3,4,5]
sqr_list = list(map(lambda x: x**2, nlist))
sqr_list
Out[20]:
[1, 4, 9, 16, 25]
In [ ]:
 

3. reduce(func, seq)

In [22]:
# functools 모듈 불러오기
from functools import reduce

a = [1, 2, 3, 4]
n = reduce(lambda x, y: x*y, a)
n
Out[22]:
24
In [23]:
# reduce 함수 사용하여 1 ~ 100 합 구하기
from functools import reduce
s = reduce(lambda x, y: x+y, list(range(1,101)))
s
Out[23]:
5050
In [24]:
# reduce 함수 이용하여 10! 구하기
f = reduce(lambda x,y: x*y, list(range(1,11)))
f
Out[24]:
3628800
In [25]:
# filter(), lambda 이용한 필터링
ages = [34, 39, 29, 18, 13, 54]
adult = list(filter(lambda x : x>=19, ages))
adult
Out[25]:
[34, 39, 29, 54]
In [ ]:
 

4. 리스트 축약

In [27]:
# list 축약을 이용한 필터링
adult1 = [x for x in ages if x>=19]
adult1
Out[27]:
[34, 39, 29, 54]
In [28]:
# 리스트 축약을 이용한 6의 배수 구하기
nlist = list(range(1,31))
six = [x for x in nlist if x % 2 == 0 if x % 3 == 0]
six
Out[28]:
[6, 12, 18, 24, 30]