• 카테고리

    질문 & 답변
  • 세부 분야

    프로그래밍 언어

  • 해결 여부

    해결됨

map,filter

23.07.23 15:16 작성 조회수 174

2

map과 filter값을 받아오기위해서는

방법이

  1. for루프

  2. list()함수

이 방법밖에 없는건가요??

그리고 map,filter인자에는 list만 들어갈수있나요?? 딕셔너리,set, 튜플등은 안되나요?

답변 1

답변을 작성해보세요.

0

안녕하세요 남기정님,

아래의 예제는 Lambda를 사용해서 쓸수 있는 방법에 대해 보실 수 있습니다.

# Sample list of integers
numbers = [1, 2, 3, 4, 5]

# Using map with a lambda function to square each element
squared_numbers = map(lambda x: x**2, numbers)

# Convert the map object to a list to see the results
result = list(squared_numbers)

# Print the squared numbers
print(result)

또한 Dictionary나 Set도 사용 가능합니다.

# Sample dictionary
my_dict = {'a': 1, 'b': 2, 'c': 3}

# Using map with a lambda function to square each value in the dictionary
squared_keys = map(lambda key: my_dict[key]**2, my_dict)

# Convert the map object to a list to see the results
result = list(squared_keys)

# Print the squared keys
print(result)