티스토리 뷰

반응형

Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.

Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.

 

아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.

How to check if a string is a substring of items in a list of strings

문자열이 문자열 리스트에 있는 항목의 부분 문자열인지 확인하는 방법

 문제 내용 

How do I search for items that contain the string 'abc' in the following list?

다음 리스트에서 문자열 'abc'가 포함된 항목을 검색하려면 어떻게 해야 합니까?
xs = ['abc-123', 'def-456', 'ghi-789', 'abc-456']

 

The following checks if 'abc' is in the list, but does not detect 'abc-123' and 'abc-456':

다음은 'abc'가 목록에 있는지 확인하지만 'abc-123' 및 'abc-456'은 검색하지 않습니다:
if 'abc' in xs:

 

 

 높은 점수를 받은 Solution 

To check for the presence of 'abc' in any string in the list:

리스트의 문자열에 'abc'가 있는지 확인하려면:
xs = ['abc-123', 'def-456', 'ghi-789', 'abc-456']

if any("abc" in s for s in xs):
    ...

To get all the items containing 'abc':

'abc'가 포함된 모든 항목을 가져오려면:
matching = [s for s in xs if "abc" in s]

 

 

 가장 최근 달린 Solution 

If you want to get list of data for multiple substrings

여러 부분 문자열에 대한 데이터 목록을 가져오려는 경우

 

you can change it this way

당신은 그것을 이렇게 바꿀 수 있다
some_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
# select element where "abc" or "ghi" is included
find_1 = "abc"
find_2 = "ghi"
result = [element for element in some_list if find_1 in element or find_2 in element] 
# Output ['abc-123', 'ghi-789', 'abc-456']

 

 

출처 : https://stackoverflow.com/questions/4843158/how-to-check-if-a-string-is-a-substring-of-items-in-a-list-of-strings

반응형
댓글
공지사항
최근에 올라온 글