우리가 일반적으로 list에서 원하는 value의 index를 찾을 때는 list.index()의 함수를 사용한다.
예로, answer라는 list에서 원소 4의 위치를 알고 싶다라고 가정한다.
answer = [1, 2, 3, 4, 5, 6]
그럴 경우에는 list.index()의 함수를 사용하여 확인한다.
print(answer.index(4)) # 결과 값 : 3
하지만, 원하는 value가 중복되었다면?
answer = [1, 2, 3, 3, 4, 4, 4, 6, 6]
앞서 list.index() 함수를 사용하면 제일 앞에 있는 위치를 반환한다.
나는 value를 가지는 모든 index를 다 얻고 싶기에, filter 함수를 사용하여 얻을 수 있다.
list나 dictionary 같은 iterable 한 데이터를 특정 조건에 일치하는 값만 추출해 낼 때 사용하는 함수이다.filter(function, iterable)
Construct an iterator from those elements of iterable for which function is true. iterable may be either a sequence, a container which supports iteration, or an iterator. If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed.
filter 함수는 일반적인 function을 정의하여 사용할 수도 있고 간단한 조건일 경우에는 lambda와 함께 사용하여 간결하게 작성한다.
def max(x):
if x > 0:
return x
else:
retun None
list(filter(max, range(-5, 10)))
>>> [1, 2, 3, 4, 5, 6, 7, 8, 9]
lambda와 함께 사용할 경우list(filter(lambda x: x > 0, range(-5, 10)))
>>> [1, 2, 3, 4, 5, 6, 7, 8, 9]
앞서 설명한 filter 함수를 사용하여 원하는 value의 다중 index를 찾을 수 있다. ✌
answer_list = list(filter(lambda x : answer_list[x] == 4, range(len(answer_list))))
print(answer_list)
# 결과 값 : [4, 5, 6]
Programmers LEVEL 0 최빈값 구하기 문제
https://school.programmers.co.kr/learn/courses/30/lessons/120812
[Refernces]
https://bill1224.tistory.com/228
https://bluese05.tistory.com/66
https://docs.python.org/3/library/functions.html#filter