我有以下功能:
def read_data(file_location):
for line in open(file_location):
# pre-process the line
yield line
def transform_1(data):
for line in data:
# change line in some way
yield line
def transform_2(data):
for line in data:
# change line in some other way
yield line
def process_file(file_location):
# Some description
#
# returns:
# generator
data = read_data(file_location)
data = transform_1(data)
data = transform_2(data)
return data
我想做的是从文件中读取行,使用多个函数转换每一行,然后对结果行执行某些操作。我不想一次读取所有行,因为文件很大。
我的问题是我这样做是否正确。代码执行正确,但是我脑子里的程序执行感觉很复杂,以至于我不知道一个月左右的时间我是否能够处理这段代码。
所以我想知道的是:是否有某种编程模式可以显示如何正确地将生成器相互链接?
最佳答案
假设每行都以相同的方式转换,您可以将转换函数应用于每行并使用生成器迭代所有行,我个人认为这更具可读性。
def transform_1(line):
return line.replace(' ','') # example of transformation
def transform_2(line):
return line.strip('#')
def process_file(file_location):
with open(file_location) as in_f:
for line in in_f:
yield transform_2(transform_1(line))
根据转换的作用,它们可能会组合成一个函数,但如果没有更多上下文,就很难知道。
关于python - 如何编写良好的生成器链接函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47394184/