如果字符串包含指定字符

时间:2018-10-11 16:00:40

标签: python list

具有以下条件:

list1 = ['something',"somet'hing",'somet"hing','some;thing','']
list2 = [';','"',"'"]

如果list内的字符串包含list2的任何字符或字符串为空,我想过滤列表1。所需的输出:

list3 = ['something']

目前,我正在手动执行以下操作:

list1withoutEmptyLines= list(filter(None, list1))
list1withoutQuote = [x for x in list1withoutEmptyLines if "'" not in x]
list1withoutDoublequotes = [x for x in list1withoutQuote if "\"" not in x]
list1withoutSemicolon = [x for x in list1withoutDoublequotes if ";" not in x]

,并且效果很好。我还尝试通过创建像这样的禁止字符列表来自动化它:

forbiddenCharacters = ['"', ';', '\'']
filteredLines = []

for character in forbiddenCharacters:
    filteredLines = [x for x in uniqueLinesInFile if character not in x]

,但称为filteredLines的列表仍包含带有分号“;”的字符串。任何建议将不胜感激。

1 个答案:

答案 0 :(得分:3)

您可以将list comprehension与内置函数any结合使用:

list1 = ['something', "somet'hing", 'somet"hing', 'some;thing', '']
list2 = [';', '"', "'"]

result = [s for s in list1 if s and not any(c in s for c in list2)]
print(result)

输出

['something']

列表理解等效于:

result = []
for s in list1:
    if s and not any(c in s for c in list2):
        result.append(s)