[Python] list에서 원하는 value를 가지는 다중 index 찾기

정은·2023년 4월 14일

PYTHON

목록 보기
1/6
post-thumbnail

우리가 일반적으로 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 함수를 사용하여 얻을 수 있다.

python - filter()

  • filter 함수는 built-in 함수로 listdictionary 같은 iterable 한 데이터를 특정 조건에 일치하는 값만 추출해 낼 때 사용하는 함수이다.
    • 아래에는 Python docs에서 서술된 filter 설명이다.

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와 함께 사용하여 간결하게 작성한다.

  1. 일반적인 함수로 작성할 경우
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]
  1. lambda와 함께 사용할 경우
list(filter(lambda x: x > 0, range(-5, 10)))

>>> [1, 2, 3, 4, 5, 6, 7, 8, 9]

list에서 value의 다중 index 찾기

앞서 설명한 filter 함수를 사용하여 원하는 value의 다중 index를 찾을 수 있다. ✌

answer_list = list(filter(lambda x : answer_list[x] == 4, range(len(answer_list))))
print(answer_list)

# 결과 값 : [4, 5, 6]

관련 문제 🤷‍♀️

[Refernces]
https://bill1224.tistory.com/228
https://bluese05.tistory.com/66
https://docs.python.org/3/library/functions.html#filter

profile
정니의 이런거 저런거 기록 일지 😛

0개의 댓글