我有一个像
这样的字符串列表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']
我正在为用户提供一个文本区域,用户可以在其中编写与上面列表中的Env匹配的任何子字符串
用户可以输入以空格分隔的子字符串: - 亚太中国
所以我必须显示一个包含APAC和CHINA
的列表List =['APAC_CHINA_UAT_D2','APAC_CHINA_UAT_D5']
如果用户输入: - AMER UAT
然后列表将是
List = ['AMER_US_T8_UAT','AMER_US_W2_UAT']
同样适用于: - AMER US T8 UAT
我只能获得一个列表List = ['AMER_US_T8_UAT']
答案 0 :(得分: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']