查找包含给定列表中子字符串的字符串

时间:2018-05-10 18:37:20

标签: python-3.x

给出两个数组:

a = ['apple', 'banana', 'orange']
b = ['TOR_apple_impact', 'TOR_apple_staging', 'TOR_banana_impact', 'TOR_banana_STAGING', 'TOR_orange_IMPACT', 'TOR_orange_STAGING']

创建第三个列表,其中包含列表b中的字符串,其中包含列表a中任何字符串的子字符串。对于上面的数组,将返回以下内容:

c = ['TOR_apple_impact', 'TOR_apple_staging', 'TOR_banana_impact', 'TOR_banana_STAGING', 'TOR_orange_IMPACT', 'TOR_orange_STAGING']

另一个例子如下所示:

a = ['apple', 'banana']
b = ['TOR_apple_impact', 'TOR_apple_staging', 'TOR_banana_impact', 'TOR_banana_STAGING', 'TOR_orange_IMPACT', 'TOR_orange_STAGING']
# would return the following list.
c = ['TOR_apple_impact', 'TOR_apple_staging', 'TOR_banana_impact', 'TOR_banana_STAGING'

这是我试过的

def build_systems_to_query(self, source_systems):
    systems_to_query = []
    for i in source_systems:
            systems_to_query.append('TOR' + '_' + i)
            systems_to_query.append('TOR' + '_' + i)
    return systems_to_query

1 个答案:

答案 0 :(得分:2)

选项1
纯python,列表理解

>>> [i for i in b if any(j in i for j in a)]
['TOR_apple_impact',
 'TOR_apple_staging',
 'TOR_banana_impact',
 'TOR_banana_STAGING'
]

选项2
re.search

>>> import re
>>> p = re.compile('|'.join(a))
>>> [i for i in b if p.search(i)]
['TOR_apple_impact',
 'TOR_apple_staging',
 'TOR_banana_impact',
 'TOR_banana_STAGING'
]