2014-08-27 104 views
0

多個子我有一個像搜索從一個字符串在python

Env = [ 
    'APAC_CHINA_UAT_D2','APAC_CHINA_UAT_D5','APAC_INDIA_Q1_UAT', 
    'AMER_US_T8_UAT','AMER_US_W2_UAT','AMER_US_Q9_PROD', 
    'EMEA_UK_K8_UAT','EMEA_DUBAI_QA_UAT'] 

我給用戶一個文本區域,在那裏用戶可以寫任何字符串相匹配的信封在上面的列表中的字符串列表

用戶可以輸入SUBSTRING由空格隔開: - APAC中國

所以我必須顯示包含APAC和中國

List =['APAC_CHINA_UAT_D2','APAC_CHINA_UAT_D5'] 
列表

如果用戶輸入: - AMER UAT

則列表將

List = ['AMER_US_T8_UAT','AMER_US_W2_UAT'] 

同樣爲: - AMER美國T8 UAT

我會得到只有一個列表List = ['AMER_US_T8_UAT']

回答

0

你輸入:

Env = [ 
    'APAC_CHINA_UAT_D2', 
    'APAC_CHINA_UAT_D5', 
    'APAC_INDIA_Q1_UAT', 
    'AMER_US_T8_UAT', 
    'AMER_US_W2_UAT', 
    'AMER_US_Q9_PROD', 
    'EMEA_UK_K8_UAT', 
    'EMEA_DUBAI_QA_UAT'] 
search = 'APAC CHINA' 

詳細,長度Ÿ版本:

List = []       # empty result list 
for e in Env:      # for each item e of Env 
    contains = True    # initially assume that e contains each search string 
    for s in search.split():  # for each word s in the search string (split at whitespace) 
     if not s in e.split('_'): # if e (split at '_') does not contain search string s 
      contains = False  # e does *not* contain each search string 
    if contains:     # if e contains all search strings 
     List.append(e)    # append e to result list 
print List       # print result list 

一行代碼:

print [e for e in Env if all([s in e.split('_') for s in search.split()])] 

輸出:

['APAC_CHINA_UAT_D2', 'APAC_CHINA_UAT_D5'] 
相關問題