Built-in Functions
파이썬에는 이미 만들어진 많은 내장함수들이 존재하지만 오늘은 map, zip, filter, enumerate를 공부하고 정리해보려고 한다. 나도 여기저기서 자주 보았고, 사용도 해봤지만 할때마다 기억이 잘 안나서 이번 기회에 제대로 정리해두려고 한다.
1. map
- map(function, iterable, *iterables)
- map은 입력된 iterable에 function이 적용된 iterator를 반환한다.
- function에는 내장함수, 람다함수, method 등을 사용할 수 있다.
data = list(range(10))
data
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
1.1 Python 내장함수 사용
- str() 함수 활용하여 data의 내용을 string으로 타입 변환
data_to_str = map(str, data)
list(data_to_str)
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
1.2 lambda 함수 활용
result = map(lambda x: x*2, data)
list(result)
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
data_1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
data_2 = [0, 1, 2, 3, 5, 8, 13, 21, 34, 55]
list(map(lambda x, y: x+y, data, data_2))
[0, 2, 4, 6, 9, 13, 19, 28, 42, 64]
1.3 임의로 만든 method 활용
def multiplication_three(x):
return x*3
result = map(multiplication_three, data)
list(result)
[0, 3, 6, 9, 12, 15, 18, 21, 24, 27]
2. filter
- filter(function, iterable)
- function에 의해 True를 반환하는 값만 필터링 한다
data
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
2.1 lambda 함수 활용
result = filter(lambda x: True if x % 2 == 1 else False, data)
list(result)
[1, 3, 5, 7, 9]
2.2 선언한 method 활용
def division_three(x):
if x % 3 == 0:
return True
else:
return False
result = filter(division_three, data)
list(result)
[0, 3, 6, 9]
3. zip
- zip(*iterables, strict=False)
- 서로 다른 자료형을 묶어주는 기능을 한다
- size가 작은 iterable이 있다면 그 크기에 맞춰서 묶어준다
data1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
data2 = [11, 22, 33, 44, 55, 66, 77, 88, 99, 100]
data3 = [5, 6, 7]
result = zip(data1, data2)
list(result)
[(1, 11), (2, 22), (3, 33), (4, 44), (5, 55),
(6, 66), (7, 77), (8, 88), (9, 99), (10, 100)]
result = zip(data1, data2, data3)
list(result)
[(1, 11, 5), (2, 22, 6), (3, 33, 7)]
3.1 zip을 활용한 dictionary 만들기
number = [1, 2, 3, 4]
seasons = ['Spring', 'Summer', 'Fall', 'Winter']
dic = {}
for number, seasons in zip(number,seasons):
dic[number] = seasons
dic
{1: 'Spring', 2: 'Summer', 3: 'Fall', 4: 'Winter'}
4. enumerate
- enumerate(iterable, start=0)
- itorator를 입력받아 index를 포함한 enumerate 객체를 반환한다
- strat는 시작 index를 지정할 수 있다.
seasons = ['Spring', 'Summer', 'Fall', 'Winter']
list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
for idx, value in enumerate(seasons):
print(f'인덱스: {idx}, 값: {value}')
인덱스: 0, 값: Spring
인덱스: 1, 값: Summer
인덱스: 2, 값: Fall
인덱스: 3, 값: Winter
Reference
'Programming Language > Python' 카테고리의 다른 글
[Python] 삼항 연산자(Ternary Operator) (0) | 2023.01.25 |
---|---|
[Python] List : Pop, Del, Remove, Slicing 속도 비교 (0) | 2023.01.19 |
[Python] 자료구조 : Hash (0) | 2022.12.27 |
[Web Crawling] Requests 와 URLLIB (0) | 2022.12.09 |
[Web Crawling] 웹 크롤링 개요 (0) | 2022.12.09 |
댓글