【问题标题】:Remove a line that contains a word from a list从列表中删除包含单词的行
【发布时间】:2021-07-21 09:16:15
【问题描述】:

有这样一个字符串:

machine1 volumename1 space1
machine1 volumename2 space2
machine2 volumename1 space1
machine2 volumename2 space2
machine3 volumename1 space1

我想删除包含一个列表元素的所有行,例如:

list = ["machine1", "machine3"]

最后收到这样的东西:

machine2 volumename1 space1
machine2 volumename2 space2

我试过这个,但它返回一个列表,我不想改变字符串的原始格式,我想使用一个机器列表作为输入:

output = str([line for line in output.split('\n') if 'machine1' not in line and 'machine3' not in line])

【问题讨论】:

    标签: python string list


    【解决方案1】:

    尝试使用\n,将any 用于list

    lst = ["machine1", "machine3"]
    print('\n'.join([line for line in output.splitlines() if not any(i in line for i in lst)]))
    

    输出:

    machine2 volumename1 space1
    machine2 volumename2 space2
    

    【讨论】:

    • 显式列表是不必要的,有点浪费; join() 可以处理生成器表达式。
    • @tripleee 性能好,我通常使用括号,检查this
    • @tripleee haha​​ 是的,来自 raymond hettinger。
    【解决方案2】:

    '\n'.join() 过滤后的列表重新组合在一起。

    output = '\n'.join(line for line in output.splitlines() if 'machine1' not in line and 'machine3' not in line)
    

    如果您仅显式检查第一个字段和整个第一个字段,那么如果您显式 split() 退出第一个字段并仅检查该字段,则代码将更加精确和健壮,甚至可能更快。

    output = '\n'.join(line for line in ouput.splitlines()
        if line.split()[0] not in ['machine1', 'machine3'])
    

    【讨论】:

      【解决方案3】:

      使用any 关键字来避免列表中的任何项目,而不是使用str 转换为字符串,而是使用"connector".join(list),如打印函数所示。

      附带说明一下,您确实不应该使用像 list 这样的关键字来命名变量,因此我已将该变量名称更改为 lst

      output = """machine1 volumename1 space1
      machine1 volumename2 space2
      machine2 volumename1 space1
      machine2 volumename2 space2
      machine3 volumename1 space1"""
      lst = ["machine1", "machine3"]
      
      output = [line for line in output.split('\n') if not any(w in line for w in lst)]
      print("\n".join(output))
      

      输出:

      machine2 volumename1 space1
      machine2 volumename2 space2
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-06-13
        • 1970-01-01
        • 1970-01-01
        • 2021-07-20
        • 1970-01-01
        • 1970-01-01
        • 2021-12-29
        • 2021-10-27
        相关资源
        最近更新 更多