我编写了一个函数来选择性地从文件中提取数据。我只想从某一行中提取,并且只提取给定的行。
当我需要处理大型文件时,将此函数转换为生成器会提高开销吗?
import itertools
import csv
def data_extraction(filename,start_line,lenght,span_start,span_end):
with open(filename, "r") as myfile:
file_= csv.reader(myfile, delimiter=' ') #extracts data from .txt as lines
return (x for x in [filter(lambda a: a != '', row[span_start:span_end]) \
for row in itertools.islice(file_, start_line, lenght)])发布于 2016-09-22 19:32:08
中使用圆括号
此外,x for x in也没有必要:
return (filter(lambda a: a != '', row[span_start:span_end]) \
for row in itertools.islice(file_, start_line, lenght))如果使用Python2,则应该使用itertools.ifilter,因为它返回生成器,而filter返回列表。
总的来说,函数是非常清楚的,我建议您按照PEP8约定将您的论证列表进行空间设置。还研究了更容易记住的参数格式,比如f(file, line_range, inline_range),其中两个元组替换了4个参数。
https://codereview.stackexchange.com/questions/142142
复制相似问题