如何使用返回列表作为另一个函数输入的函数?

2024-06-16 11:59:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我首先编写了一个函数,它包含18个参数,并将它们转换成6个不同的列表。代码如下:

def list_maker(val1,val2,val3,val4,val5,val6,val7,val8,val9,por1,por2,por3,hth1,hth2,hth3,sat1,sat2,sat3):

#Make the voip list
list1 = [val1,val2,val3]
list2 = [val4,val5,val6]
list3 = [val7,val8,val9]

#Make the variable list
list_por = [por1,por2,por3]
list_hth = [hth1,hth2,hth3]
list_sat = [sat1,sat2,sat3]

return list1,list2,list3,list_por,list_hth,list_sat

这部分工作得很好(我会让它看起来更好,一旦它真的工作)。 现在,我的想法是使用这个函数作为下面另一个函数的输入来创建绘图:

def graph_maker(listx1,listx2,listx3,list1,list2,list3):

#plot the saturation graph
por_plot = plt.plot(listx1,list1)
por_plot.ylabel('VOIP')
por_plot.xlabel('Porosity')
por_plot.show()

#plot the heigth graph
hth_plot = plt.plot(listx2,list2)
hth_plot.ylabel('VOIP')
hth_plot.xlabel('Height')
hth_plot.show()

#plot the saturation graph
sat_plot = plt.plot(listx3,list3)
sat_plot.ylabel('VOIP')
sat_plot.xlabel('Saturation')
sat_plot.show()

所以我用以下两行代码运行代码:

list_maker(voip1,voip2,voip3,voip4,voip5,voip6,voip7,voip8,voip9,0.3,0.2,0.15,100,150,200,0.8,0.6,0.5)
graph_maker(list_maker)

我得到的错误是:

graph_maker() missing 5 required positional arguments: 'listx2', 'listx3', 'list1', 'list2', and 'list3'

据我所知,似乎list\u maker()实际上只返回一个列表,显然graph\u maker函数需要6个参数。有什么想法吗

谢谢你的帮助


Tags: the函数plotpltsatlistgraphmaker
2条回答

在外部函数调用中缺少内部函数调用的一部分:

graph_maker(list_maker)
graph_maker(*list_maker(vars))

或者将您的初始函数调用赋给一个变量,并使用*解压这些值(归功于@zondo)

x=list_maker(voip1,voip2,voip3,voip4,voip5,voip6,voip7,voip8,voip9,0.3,0.2,0.15,100,150,200,0.8,0.6,0.5)
graph_maker(*x)

马可,当你把list_maker传递给graph_maker时,你实际上并没有把函数的结果(你想要的列表)作为输入传递给graph\u maker,而是把函数传递给它

但这不是一个简单的问题:

result = list_maker(voip1,voip2,voip3,voip4,voip5,voip6,voip7,voip8,voip9,0.3,0.2,0.15,100,150,200,0.8,0.6,0.5)
graph_maker(result)

由于函数list\u maker返回一个包含所有列表的元组,因此需要按以下方式展开它们:

result = list_maker(voip1,voip2,voip3,voip4,voip5,voip6,voip7,voip8,voip9,0.3,0.2,0.15,100,150,200,0.8,0.6,0.5)
graph_maker(*result)

星号将元组扩展为函数所需的5个参数,这有意义吗

相关问题 更多 >