简体   繁体   English

将多个参数传递给多个元组集中的函数-python

[英]pass multiple parameters to function in multiple tuple sets - python

essentially I have a function which I need to pass to a bunch of values in two different moments (here skipped for practical reasons), hence, I thought need to split all the parameters in two tuple sets after which I'd pass the first set and then the second thinking - mistakenly - that python would allocate all the available n parameters of the function to the values passed with the tuple and then the rest with the second tuple. 本质上,我有一个函数,需要在两个不同的时刻将其传递给一堆值(出于实际原因在此跳过),因此,我认为需要将所有参数拆分为两个元组组,然后再传递第一组然后第二种想法-错误地-python将把函数的所有可用n参数分配给元组传递的值,然后将其余的分配给第二元组。 That is not the case: 事实并非如此:

def example_F_2(x, y, z, g):
    return x * y + z * g

e = (1,2)
r = (3,4)
print(example_F_2(e, r))

in fact: 事实上:

Traceback (most recent call last):
  File "C:/Users/francesco/PycharmProjects/fund-analysis/test_sheet.py", line 7, in <module>
    print(example_F_2(e, r))
TypeError: example_F_2() missing 2 required positional arguments: 'z' and 'g'

what can I do? 我能做什么? I am guessing something from this page should work ( https://docs.python.org/3.5/library/functools.html ) but I have been unable to do it myself 我猜测此页面上的某些内容应该可以工作( https://docs.python.org/3.5/library/functools.html ),但我自己却无法执行此操作

一种非常简单的方法是连接元组,然后在将它们传递给函数时解压缩它们:

print(example_F_2(*(e+r)))

Perhaps you can use something like this: 也许您可以使用如下所示的内容:

def example_F_2(e=None, r=None):
    first_term = 0
    second_term = 0
    if e is not None:
        first_term = e[0] * e[1]
    if r is not None:
        second_term = r[0] * r[1]
    return first_term + second_term


e = (1, 2)
r = (3, 4)
print example_F_2(e, r)
> 14
print example_F_2(e=e)
> 2
print example_F_2(r=r)
> 12

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM