528

配列内の文字列のいずれかが別の文字列に存在するかどうかを確認するにはどうすればよいですか?

お気に入り:

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"

そのコードは機能しません。達成したいことを示すだけです。

4

16 に答える 16

1017

使用できますany

a_string = "A string is more than its parts!"
matches = ["more", "wholesome", "milk"]

if any(x in a_string for x in matches):

同様に、リストのすべてallの文字列が見つかったかどうかを確認するには、代わりに を使用しanyます。

于 2010-08-02T16:15:25.513 に答える
53

の紐が長くなっaたりする場合は注意が必要です。str簡単な解決策は O(S*(A^2)) です。ここで、Sは の長さstr、A は 内のすべての文字列の長さの合計ですa。より高速なソリューションについては、線形時間 O(S+A) で実行される文字列一致のAho-Corasickアルゴリズムを見てください。

于 2010-08-02T19:04:58.177 に答える
32

で多様性を追加するだけ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))

于 2016-05-23T21:45:58.990 に答える
14

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"
于 2010-08-02T16:15:53.627 に答える
3
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"
于 2010-08-02T16:16:40.673 に答える
1

単一のリテラルのような(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")
于 2016-11-30T05:17:45.867 に答える