配列内の文字列のいずれかが別の文字列に存在するかどうかを確認するにはどうすればよいですか?
お気に入り:
a = ['a', 'b', 'c']
str = "a123"
if a in str:
print "some of the strings found in str"
else:
print "no strings found in str"
そのコードは機能しません。達成したいことを示すだけです。
の紐が長くなっa
たりする場合は注意が必要です。str
簡単な解決策は O(S*(A^2)) です。ここで、S
は の長さstr
、A は 内のすべての文字列の長さの合計ですa
。より高速なソリューションについては、線形時間 O(S+A) で実行される文字列一致のAho-Corasickアルゴリズムを見てください。
で多様性を追加するだけregex
です:
import re
if any(re.findall(r'a|b|c', str, re.IGNORECASE)):
print 'possible matches thanks to regex'
else:
print 'no matches'
またはリストが長すぎる場合 -any(re.findall(r'|'.join(a), str, re.IGNORECASE))
a の要素を反復処理する必要があります。
a = ['a', 'b', 'c']
str = "a123"
found_a_string = False
for item in a:
if item in str:
found_a_string = True
if found_a_string:
print "found a match"
else:
print "no match found"
a = ['a', 'b', 'c']
str = "a123"
a_match = [True for match in a if match in str]
if True in a_match:
print "some of the strings found in str"
else:
print "no strings found in str"
単一のリテラルのような(a、e、w、..などの単一の単語)をチェックしたい場合は、コンテキストに依存します
original_word ="hackerearcth"
for 'h' in original_word:
print("YES")
original_wordの文字を確認したい場合:
if any(your_required in yourinput for your_required in original_word ):
そのoriginal_wordに必要なすべての入力が必要な場合は、すべての単純なものを使用してください
original_word = ['h', 'a', 'c', 'k', 'e', 'r', 'e', 'a', 'r', 't', 'h']
yourinput = str(input()).lower()
if all(requested_word in yourinput for requested_word in original_word):
print("yes")