【发布时间】:2018-10-11 16:00:40
【问题描述】:
有以下几点:
list1 = ['something',"somet'hing",'somet"hing','some;thing','']
list2 = [';','"',"'"]
如果列表中的字符串包含来自 list2 的任何字符或字符串为空白,我想获得过滤的 list1。期望的输出:
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 的列表仍然包含带有分号“;”的字符串。任何建议将不胜感激。
【问题讨论】:
-
[x for x in list1 if not any(y in x for y in list2)] -
您在每次迭代中都会覆盖
filteredLines。