python-3.x 字符串在列表中搜索(如果列表包含带空格的字符串

eeq64g8w  于 2023-02-14  发布在  Python
关注(0)|答案(2)|浏览(116)

我想识别列表中的一个单词,但是其中一个字符串之间有空格,无法识别。

res = [word for word in somestring if word not in myList]

myList = ["first", "second", "the third"]

所以当

somestring = "test the third"

则解析为res="test the third"(应为"test"")。
如果列表中包含一个带空格的字符串,如何克服列表中的字符串搜索?

yptwkmov

yptwkmov1#

一种方法是使用split()

myList = ["first", "second", "the third"]

somestring = "test the third" 

n=[x.split() for x in myList]
#[['first'], ['second'], ['the', 'third']]

您可以通过以下方式展平此对象:

m=[item for sublist in n for item in sublist]
#['first', 'second', 'the', 'third']

类似地,您可以split() somestring

s=somestring.split()
#['test', 'the', 'third']

最后:

for x in s:
  if x not in m:
    print(x)
#test

也可以在一行中得到结果;但可读性不是很强:

[x for x in somestring.split() if x not in (item for sublist in (x.split() for x in myList) for item in sublist)]
#['test']
ajsxfq5m

ajsxfq5m2#

使用myLst作为正则表达式替换的模式列表:

import re

myList = ["first", "second", "the third"]
somestring = "test the third"
res = re.sub(fr'({"|".join(myList)})', '', somestring).strip()
print(res)
test

相关问题