【问题标题】:Removing string from list if string contain specified character如果字符串包含指定字符,则从列表中删除字符串
【发布时间】: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

标签: python list


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-24
    • 1970-01-01
    • 2020-02-14
    • 2018-11-05
    • 2015-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多