티스토리 뷰
Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.
Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.
아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.
Is there a short contains function for lists?
리스트에 대한 간단한 포함 여부 체크하는 함수가 있나요?
문제 내용
Given a list xs
and a value item
, how can I check whether xs
contains item
(i.e., if any of the elements of xs
is equal to item
)? Is there something like xs.contains(item)
?
리스트 xs와 값 item이 주어졌을 때, xs가 item을 포함하는지 (즉, xs의 요소 중 하나가 item과 같은지) 확인하는 방법은 무엇인가요? xs.contains(item)와 같은 것이 있나요?
For performance considerations, see Fastest way to check if a value exists in a list.
성능 고려 사항은 Fastest way to check if a value exists in a list를 참조하세요.
높은 점수를 받은 Solution
Use:
사용법:
if my_item in some_list:
...
Also, inverse operation:
또한, 역으로 포함되지 않을 때는:
if my_item not in some_list:
...
It works fine for lists, tuples, sets and dicts (check keys).
이것은 리스트, 튜플, 집합 및 dict(키를 확인)에서 잘 작동합니다.
Note that this is an O(n) operation in lists and tuples, but an O(1) operation in sets and dicts.
리스트와 튜플에서는 이것이 O(n) 연산임에 유의하세요. 하지만 set과 dict에서는 O(1) 연산입니다.
가장 최근 달린 Solution
I came up with this one liner recently for getting True
if a list contains any number of occurrences of an item, or False
if it contains no occurrences or nothing at all. Using next(...)
gives this a default return value (False
) and means it should run significantly faster than running the whole list comprehension.
저는 최근에 이 한 줄 코드를 만들었습니다. 리스트에 항목이 하나도 없거나 아무것도 없으면 False를 기본값으로 반환하므로 next(...)를 사용하여 전체 리스트 내포보다 훨씬 빠르게 실행됩니다.
list_does_contain = next((True for item in list_to_test if item == test_item), False)
출처 : https://stackoverflow.com/questions/12934190/is-there-a-short-contains-function-for-lists
'개발 > 파이썬' 카테고리의 다른 글
.py 파일과 .pyc 파일의 차이점 (0) | 2023.02.03 |
---|---|
JSON 파일 로드하고 파싱하기 (0) | 2023.02.02 |
Python에서 파일 읽기 및 덮어쓰기 (0) | 2023.02.01 |
문자열 리스트에 특정 문자열이 있는지 확인하기 (0) | 2023.01.31 |
데이터프레임에서 특정 값과 일치하는 열의 행 인덱스 가져오기 (0) | 2023.01.29 |