在这种情况下如何使用args来防止多次调用函数?

问题描述 投票:0回答:1

我有一个多线绘图仪,它接收n个列表[u,u1 ...]列表的参数,基本上在单个图形上绘制n行。但是,为了绘制它们,我必须从我的其他函数调用它们,它返回不同T = 50,150的单个列表,...

x, u = heat_eq(50, both_ice, 0, 0)   # here im calling 8 lists to plot them
x, u2 = heat_eq(150, both_ice, 0, 0)
x, u3 = heat_eq(250, both_ice, 0, 0)
x, u4 = heat_eq(350, both_ice, 0, 0)
x, u5 = heat_eq(450, both_ice, 0, 0)
x, u6 = heat_eq(550, both_ice, 0, 0)
x, u7 = heat_eq(650, both_ice, 0, 0)
multiline(x, [u, u2, u3, u4, u5, u6], "length(m)", "Temperature(Degree Celsius)", [25, 50, 250, 350, 450, 550, 650], "time(s)", 21)

在这种情况下,如果我要绘制更多的线条,我的heat_eq()将被多次调用。有没有一种方法可以将循环与* args组合在一起,这样它就可以实现

for i in range(*args):
      x, [u, u2, u3, u4, ...] = heat_eq("different T(s) here", both_ice, 0, 0)
return x, [u, u2, u3, ...]

这样我就可以

multiline(x, [u, u2, u3, u4, ...], "length(m)", "Temperature(Degree Celsius)", [25, 50, 250, 350, 450, 550, 650], "time(s)", 21)

?对args的操纵实际上非常令人困惑。

编辑:以为我会提供更多关于我的功能的信息,以帮助您更好地理解问题。所以我的heat_eq是这样的:

def heat_eq(T, bc, ti, tf):
"""
T is a number here
bc is the boundary condition function
ti and tf are both constants
"""
t = np.linspace(0, T, Nx + 1)
x = np.linspace(0, T, Nx + 1)
# define other stuff here


# initiate a matrix here
A = some matrix
A = bc(A, some other constants)  # A gets put into BC spits out A with boundary condition values included.
for n in range(something):
    Here A does something to produce data points into a list u

return x, u

因此,当我称之为边界条件both_ice(A, constant)我会这样做

x, u = heat_eq(50, both_ice, 0, 0)

希望这是足以让您理解问题的信息。

python-3.x arguments parameter-passing args
1个回答
0
投票

我建议你heat_eq收到一个列表作为输入参数

def heat_eq(my_list):
    # Do whatever
    return x, another_list

如果您希望将参数解压缩为*args,则应将both_ice, 0, 0传递给命名参数,然后您将能够将每个未命名的参数解压缩为列表:

def both_ice():
   pass

def heat_eq(*args, func=both_ice, num_1=0, num_2=0):
    # Now you have a list of arguments
    for elem in args:
        do_whatever(elem)
    return x, list_of_elems
© www.soinside.com 2019 - 2024. All rights reserved.