我有以下代码,我扫描每一行并放入一个列表。如果该行匹配 一个字符串“New changes”,我不想把它放在列表中。有关如何实现这一目标的任何建议吗?
with open('file.txt', 'rb') as f:
mainlist = [line.strip() for line in f]
答案 0 :(得分:3)
您可以在列表理解中进行过滤:
mainlist = [line.strip() for line in f if line.strip() != "New changes"]
答案 1 :(得分:2)
列表推导也可以进行过滤:
mainlist = [line.strip() for line in f if "New changes" not in line]
答案 2 :(得分:0)
with open('file.txt', 'rb') as f:
mainlist = []
for line in f:
s = line.strip()
if s != "New changes":
mainlist.append(s)
如果有人有更多的pythonic方法,请随时告诉我。
答案 3 :(得分:0)
理解也可以接受一个条件。尝试:
mainlist = [line.strip() for line in f if line != "New changes"]
或
mainlist = [line.strip() for line in f if "New changes" not in line]
答案 4 :(得分:0)
这里的不同之处是来自reduce和regex学校的咒语:
import re
with open('file.txt', 'rb') as f:
mainlist = reduce(lambda x, y: x+re.findall("^((?!.*New changes).*)\n?$", y), f.readlines(), [])