gpt4 book ai didi

python - 应该如何设置一个不变的 Python 函数的参数?

转载 作者:太空宇宙 更新时间:2023-11-04 08:51:56 25 4
gpt4 key购买 nike

我有一个被调用多次的函数。它的大部分论点都发生了变化,但有一个保持不变。有没有办法不必将其作为参数包含在内?

# in a loop that changes index
data.variable(index = index, name = "el_1_pt", value = event.el_pt[0])
data.variable(index = index, name = "el_1_eta", value = event.el_eta[0])
data.variable(index = index, name = "el_1_phi", value = event.el_phi[0])
data.variable(index = index, name = "jet_1_pt", value = event.jet_pt[0])
data.variable(index = index, name = "jet_1_eta", value = event.jet_eta[0])
data.variable(index = index, name = "jet_1_phi", value = event.jet_phi[0])
data.variable(index = index, name = "jet_1_e", value = event.jet_e[0])
data.variable(index = index, name = "jet_2_pt", value = event.jet_pt[1])
data.variable(index = index, name = "jet_2_eta", value = event.jet_phi[1])
data.variable(index = index, name = "jet_2_phi", value = event.jet_eta[1])
data.variable(index = index, name = "jet_2_e", value = event.jet_e[1])
data.variable(index = index, name = "met", value = event.met_met)
data.variable(index = index, name = "met_phi", value = event.met_phi)

你可以看到没有改变的参数是index。有什么方法可以让我不必将其指定为函数的参数并使用更少的文本吗?

最佳答案

您可以使用 partial 在每个循环中创建一个偏函数:

from functools import partial
for index in indexes:
variable = partial(data.variable, index=index)
variable(name="el_1_pt", value=event.el_pt[0])
variable(name="el_1_eta", value=event.el_eta[0])
variable(name="el_1_phi", value=event.el_phi[0])
variable(name="jet_1_pt", value=event.jet_pt[0])
variable(name="jet_1_eta", value=event.jet_eta[0])
variable(name="jet_1_phi", value=event.jet_phi[0])
variable(name="jet_1_e", value=event.jet_e[0])
variable(name="jet_2_pt", value=event.jet_pt[1])
variable(name="jet_2_eta", value=event.jet_phi[1])
variable(name="jet_2_phi", value=event.jet_eta[1])
variable(name="jet_2_e", value=event.jet_e[1])
variable(name="met", value=event.met_met)
variable(name="met_phi", value=event.met_phi)

关于python - 应该如何设置一个不变的 Python 函数的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34314304/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com