简体   繁体   English

从列表中删除包含单词的行

[英]Remove a line that contains a word from a list

Having a string like this one:有这样一个字符串:

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

I would like to remove all the lines containing one element of a list, for example:我想删除包含列表中一个元素的所有行,例如:

list = ["machine1", "machine3"]

Receiving at the end something like this:最后收到这样的东西:

machine2 volumename1 space1
machine2 volumename2 space2

I tried with this, but it returns a list, and I would like to not change the original format of the string and I would like to use a list of machines as an input:我试过这个,但它返回一个列表,我不想改变字符串的原始格式,我想使用机器列表作为输入:

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

Try using \\n , and any for list :尝试使用\\nany for list

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

Output:输出:

machine2 volumename1 space1
machine2 volumename2 space2

Just '\\n'.join() the list back together after filtering it.过滤后只需'\\n'.join()将列表重新组合在一起。

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

If you are explicitly examining only the first field and the whole first field, the code will be both more precise and robust and possibly even faster if you explicitly split() out the first field and examine only that.如果您仅显式检查第一个字段和整个第一个字段,那么如果您显式地split()第一个字段split()并只检查它,代码将更加精确和健壮,甚至可能更快。

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

Use the any keyword to avoid any items from your list, and instead of converting to a string with str use "connector".join(list) as shown in the print function.使用any关键字来避免列表中的任何项目,而不是转换为带有str的字符串,而是使用"connector".join(list) ,如打印函数中所示。

As a side-note, you really shouldn't use keywords like list to name your variables, so I've changed that variable name to lst .作为旁注,您真的不应该使用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))

Output:输出:

machine2 volumename1 space1
machine2 volumename2 space2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM