학습/python
map() -1 map동작 원리, 그냥 list 안에 for 문 쓰면 안됨??
ParkParksu
2023. 5. 22. 00:06
list = [2,4,6,8,10,12,14,16,18,20]
# 사이에 들어갈 코드
print("list_square = {}".format(list_square))
Iterable 한 객체를 받아 반복할때 map 을 사용하는데
# for 문
list_square = []
for num in list:
list_square.apeend(num**2)
# map()
list_square = list(map(lambda x: x**2, a))
예시2
list2 = ["a,1", "b,2", "c,4", "d,6", "e,11"]
# 사이에 들어갈 코드
# 출력값
# str = ['a','b','c','d','e']
# num = ['1','2','4','6','11']
str = list(map(lambda x: x.split(',')[0], list2))
num = list(map(lmabda x: x.split(',')[1], list2))
map 은
map( #어떤 걸 할지를 나타내는 함수, 어떤것을 할 리스트) 를 받아서 내부적으로 for 문을 돌려주는 함수다.
map 그자체를 print 하면 amp object 로 출력된다.
그래서 list로 자료형 변환을 해준다.
근데 다 for 문으로 표현 가능하다.
list_square = list(map(lambda x: x**2, a))
list_square = [num**2 for num in a]
str = list(map(lambda x: x.split(',')[0], list2))
num = list(map(lmabda x: x.split(',')[1], list2))
str = [x.split(',')[0] for x in list2]
num = [x.split(',')[1] for x in list2]
개인적으로는 map 보다 그냥 리스트로 표현하는게 보기더 편한것 같다.
728x90