📜  Python|根据子字符串列表过滤字符串列表

📅  最后修改于: 2022-05-13 01:55:50.087000             🧑  作者: Mango

Python|根据子字符串列表过滤字符串列表

给定两个字符串substr ,编写一个Python程序来过滤掉字符串中包含substr中的字符串的所有字符串。

例子:

Input : string = ['city1', 'class5', 'room2', 'city2']
        substr = ['class', 'city']
Output : ['city1', 'class5', 'city2']

Input : string = ['coordinates', 'xyCoord', '123abc']
        substr = ['abc', 'xy']
Output : ['xyCoord', '123abc']


方法#1:使用列表推导

我们可以使用列表推导和in运算符来检查 'substr' 中的字符串是否包含在 ' 字符串' 中。

# Python3 program to Filter list of 
# strings based on another list
import re
  
def Filter(string, substr):
    return [str for str in string if
             any(sub in str for sub in substr)]
      
# Driver code
string = ['city1', 'class5', 'room2', 'city2']
substr = ['class', 'city']
print(Filter(string, substr))
输出:
['city1', 'class5', 'city2']


方法 #2: Python正则表达式

# Python3 program to Filter list of 
# strings based on another list
import re
  
def Filter(string, substr):
    return [str for str in string 
    if re.match(r'[^\d]+|^', str).group(0) in substr]
      
# Driver code
string = ['city1', 'class5', 'room2', 'city2']
substr = ['class', 'city']
print(Filter(string, substr))
输出:
['city1', 'class5', 'city2']