以pythonic方式遍历csv.reader()
作者:互联网
我正在开发一个程序,该程序使用csv.reader()读取csv等.我想将与两个条件之一匹配的变量保存在两个不同的类变量中.因为我喜欢编写列表推导,并且试图以一种更加Python化的方式编写代码,所以我想知道这是否是正确的方法. csv.reader()似乎是一个生成器对象,因为我可以对其进行一次迭代.因此,对于第二种情况,我将第二次创建读取器对象.对我来说,这似乎是一种资源浪费.当然,我可以使用普通的for循环和不同的if情况编写它.但是,有没有更Python的方式来编写这段代码?
with open(file, "r") as f:
reader = csv.reader(f, delimiter=",")
self.xitireq = [row[0] for row in reader if "xiti" in row[0]]
with open(file, "r") as f:
reader = csv.reader(f, delimiter=",")
self.apireq = [row[0] for row in reader if "https://www.blabal.de/api" in row[0]]
如果我这样写代码,self.apireq为空:
with open(file, "r") as f:
reader = csv.reader(f, delimiter=",")
self.xitireq = [row[0] for row in reader if "xiti" in row[0]]
self.apireq = [row[0] for row in reader if "https://www.blabal.de/api" in row[0]]
解决方法:
我能想到的最简单的解决方案就是这样
with open(file, "r") as f:
reader = list(csv.reader(f, delimiter=","))
self.xitireq = [x for x in reader if "xiti" in x]
self.apireq = [x for x in reader if "https://www.blabal.de/api" in x]
唯一的区别是,我根据发帖Python import csv to list和本文档https://docs.python.org/3/library/csv.html#csv.Dialect将您的阅读器转换为带有list()的列表.
此时将读取器重命名为某种名称可能更准确,但这仅是语义.
标签:python,list-comprehension 来源: https://codeday.me/bug/20191211/2105479.html