2017-09-21 12 views
0

私は部分文字列のリストを持っていて、他の文字列に部分文字列があるかどうかを調べています。 anyはbooleanを返します。文字列と一致した後に部分文字列のリストからインデックスを返します

>>> list=['oh' , 'mn' , 'nz' , 'ne'] 
>>> name='hstntxne' 
>>> any(x in name for x in list) 
True 
>>> name='hstnzne' 
>>> any(x in name for x in list) 
True 

私はインデックスを返したいと思います。例えば3回目で2回目と3回目にする必要があります。

答えて

0

を与えるだろう。 listはPythonのデータ構造体であり、特別な理由がない限り、その名前を上書きしたくないということです。

リストの理解度を1行で簡単に達成できます。

substrings = ['oh' , 'mn' , 'nz' , 'ne'] 
name1='hstntxne' 
name2='hstnzne' 

[substrings.index(x) for x in substrings if x in name1] 

これは3

[substrings.index(x) for x in substrings if x in name2] 

この戻り、[2、3]

部分文字列の任意のリストと、この作業を行うために、そして名前の関数に入れて返します。

def getIndex(subs, name): 
    return [subs.index(x) for x in subs if x in name] 

getIndex(substrings, name2) #example call 
0

組み込みenumerate()機能を使用できます。

def get_index(name, lis=['oh' , 'mn' , 'nz' , 'ne']): 
    indx = [] 
    for index, element in enumerate(lis): 
     if element in name: 
      indx.append(index) 
    return indx 

get_index(name='hstnzne')[2, 3]

get_index(name='hstntxne')を与えるだろうが、あなたのリストlistを呼び出すことはありません、まず[3]

0
import re 

# Try and use regex to see if subpattern exists 

l = ['oh', 'mn', 'nz', 'ne'] 

name='hstnzne' 
match_indx = [] 

for i, sub_str in enumerate(l): 
    result = re.split(sub_str, name) 
    if (len(result)>1): 
     # We could split our string due to match, so add index of substring 
     match_indx.append(i) 

print(match_indx) 
関連する問題