【问题标题】:How to use args to prevent multiple calls of a function in this case?在这种情况下如何使用 args 来防止函数的多次调用?
【发布时间】:2019-07-30 23:46:49
【问题描述】:

我有一个多线绘图仪,它接收 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() 将不得不被调用很多次。有没有办法将 for 循环与 *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】:

    我会建议你 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
    

    【讨论】:

    • 忘了说我这里的both_ice是一个边界条件的函数,它接受其他参数both_ice(list_a, list_b, list_c, constant)被调用到heat_eq里面使用。不确定这会如何改变您的答案?
    • 不过这不是问题,我会根据您的问题编辑答案
    • 嗨,我已经提供了有关我的问题的更多信息,请看一下:)
    猜你喜欢
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多