gpt4 book ai didi

python - 如果字符串包含指定字符,则从列表中删除字符串

转载 作者:行者123 更新时间:2023-11-30 22:06:20 26 4
gpt4 key购买 nike

具有以下内容:

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

如果列表中的字符串包含列表2中的任何字符或字符串为空,我想过滤列表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的列表仍然包含带有分号“;”的字符串。任何建议将不胜感激。

最佳答案

您可以使用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)

关于python - 如果字符串包含指定字符,则从列表中删除字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52764392/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com