我知道这是非常基本的,我一直在到处搜索,但我仍然对我所看到的一切感到非常困惑,我不确定这样做的最佳方法,并且我很难把头围绕它。
我有一个脚本,其中有多个功能。我希望第一个函数将它的输出传递给第二个函数,然后第二个函数将它的输出传递给第三个函数,依此类推。在到起始数据集的整个过程中,每个函数都有自己的步骤。
例如,用坏名字非常简化,但这只是为了获得基本结构:
#!/usr/bin/python
# script called process.py
import sys
infile = sys.argv[1]
def function_one():
do things
return function_one_output
def function_two():
take output from function_one, and do more things
return function_two_output
def function_three():
take output from function_two, do more things
return/print function_three_output
Run Code Online (Sandbox Code Playgroud)
我希望它作为一个脚本运行并将输出/写入打印到新文件或我知道如何做的任何事情。只是不清楚如何将每个函数的中间输出传递给下一个等等。
infile -> function_one -> (intermediate1) -> function_two -> (intermediate2) -> function_three -> 最终结果/输出文件
我知道我需要使用 return,但我不确定如何在最后调用它以获得我的最终输出
个人?
function_one(infile)
function_two()
function_three()
Run Code Online (Sandbox Code Playgroud)
还是彼此之间?
function_three(function_two(function_one(infile)))
Run Code Online (Sandbox Code Playgroud)
还是在实际功能中?
def function_one():
do things
return function_one_output
def function_two():
input_for_this_function = function_one()
# etc etc etc
Run Code Online (Sandbox Code Playgroud)
谢谢你的朋友,我把这个复杂化了,需要一个非常简单的方法来理解它。
小智 5
正如 ZdaR 所提到的,您可以运行每个函数并将结果存储在一个变量中,然后将其传递给下一个函数。
def function_one(file):
do things on file
return function_one_output
def function_two(myData):
doThings on myData
return function_two_output
def function_three(moreData):
doMoreThings on moreData
return/print function_three_output
def Main():
firstData = function_one(infile)
secondData = function_two(firstData)
function_three(secondData)
Run Code Online (Sandbox Code Playgroud)
这是假设您的 function_three 将写入文件或不需要返回任何内容。如果这三个函数总是一起运行,另一种方法是在 function_three 中调用它们。例如...
def function_three(file):
firstStep = function_one(file)
secondStep = function_two(firstStep)
doThings on secondStep
return/print to file
Run Code Online (Sandbox Code Playgroud)
然后你所要做的就是在你的 main 中调用 function_three 并将文件传递给它。
您可以定义一个数据流辅助函数
from functools import reduce
def flow(seed, *funcs):
return reduce(lambda arg, func: func(arg), funcs, seed)
flow(infile, function_one, function_two, function_three)
#for example
flow('HELLO', str.lower, str.capitalize, str.swapcase)
#returns 'hELLO'
Run Code Online (Sandbox Code Playgroud)
我现在建议实现上述flow
功能的一种更“pythonic”的方法是:
def flow(seed, *funcs):
for func in funcs:
seed = func(seed)
return seed;
Run Code Online (Sandbox Code Playgroud)
mik*_*keb -2
这种方式function_three(function_two(function_one(infile)))
是最好的,您不需要全局变量,并且每个函数完全独立于其他函数。
编辑添加:
我还想说 function3 不应该打印任何内容,如果你想打印返回的结果,请使用:
print function_three(function_two(function_one(infile)))
或类似的东西:
output = function_three(function_two(function_one(infile)))
print output
Run Code Online (Sandbox Code Playgroud)