티스토리 뷰

반응형

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

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

 

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

Check if multiple strings exist in another string

하나의 문자열에 여러 문자열이 있는지 확인하기

 문제 내용 

How can I check if any of the strings in an array exists in another string?

어떻게 하면 배열에 있는 문자열 중 어떤 것이라도 다른 문자열에 존재하는지 확인할 수 있을까요?

 

For example:

예를 들어:
a = ['a', 'b', 'c'] s = "a123" if a in s:     print("some of the strings found in s") else:     print("no strings found in s") 

 

How can I replace the if a in s: line to get the appropriate result?

어떻게 하면 올바른 결과를 얻기 위해 "if a in s:" 라인을 대체할 수 있을까요?

 

 

 

 높은 점수를 받은 Solution 

You can use any:

`any` 함수를 사용할 수 있습니다.
a_string = "A string is more than its parts!" matches = ["more", "wholesome", "milk"]  if any([x in a_string for x in matches]): 

 

Similarly to check if all the strings from the list are found, use all instead of any.

리스트 안의 모든 문자열이 있는지 확인하려면, any 대신 all을 사용하세요.

 

 

 

 가장 최근 달린 Solution 

A compact way to find multiple strings in another list of strings is to use set.intersection. This executes much faster than list comprehension in large sets or lists.

다른 문자열 리스트에서 여러 문자열을 찾는 간단한 방법은 set.intersection을 사용하는 것입니다. 이 방법은 대규모 집합이나 리스트에서 리스트 컴프리헨션보다 빠르게 실행됩니다.
>>> astring = ['abc','def','ghi','jkl','mno'] >>> bstring = ['def', 'jkl'] >>> a_set = set(astring)  # convert list to set >>> b_set = set(bstring) >>> matches = a_set.intersection(b_set) >>> matches {'def', 'jkl'} >>> list(matches) # if you want a list instead of a set ['def', 'jkl'] >>> 

 

 

출처 : https://stackoverflow.com/questions/3389574/check-if-multiple-strings-exist-in-another-string

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