[英]Read a file, skip unwanted lines & add into a List
我有以下代码,我在其中扫描每一行并放入列表中。 如果该行与字符串“ New changes”匹配,则我不想放入列表中。 关于如何实现这一目标的任何建议?
with open('file.txt', 'rb') as f:
mainlist = [line.strip() for line in f]
您可以在列表理解范围内进行过滤:
mainlist = [line.strip() for line in f if line.strip() != "New changes"]
列表推导也可以进行过滤:
mainlist = [line.strip() for line in f if "New changes" not in line]
with open('file.txt', 'rb') as f:
mainlist = []
for line in f:
s = line.strip()
if s != "New changes":
mainlist.append(s)
如果有人有更Python化的方法来执行此操作,请随时告诉我。
理解力也可以接受条件。 尝试:
mainlist = [line.strip() for line in f if line != "New changes"]
要么
mainlist = [line.strip() for line in f if "New changes" not in line]
与这里不同的是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(), [])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.