如何分解元组以便它可以作为参数列表传递?

发布于 2024-09-08 21:28:39 字数 335 浏览 5 评论 0原文

假设我有一个像这样的方法定义:

def myMethod(a, b, c, d, e)

然后,我有一个变量和一个像这样的元组:

myVariable = 1
myTuple = (2, 3, 4, 5)

有没有办法可以传递爆炸元组,以便我可以将其成员作为参数传递?像这样的东西(虽然我知道这不会起作用,因为整个元组被认为是第二个参数):

myMethod(myVariable, myTuple)

如果可能的话,我想避免单独引用每个元组成员......

Let's say I have a method definition like this:

def myMethod(a, b, c, d, e)

Then, I have a variable and a tuple like this:

myVariable = 1
myTuple = (2, 3, 4, 5)

Is there a way I can pass explode the tuple so that I can pass its members as parameters? Something like this (although I know this won't work as the entire tuple is considered the second parameter):

myMethod(myVariable, myTuple)

I'd like to avoid referencing each tuple member individually if possible...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

撕心裂肺的伤痛 2024-09-15 21:28:39

您正在寻找参数解包运算符*< /代码>:

myMethod(myVariable, *myTuple)

You are looking for the argument unpacking operator *:

myMethod(myVariable, *myTuple)
撧情箌佬 2024-09-15 21:28:39

来自 Python 文档


参数已在列表中或
元组,但需要解压
需要单独的函数调用
位置参数。例如,
内置 range() 函数期望
单独的开始和停止参数。如果
它们不单独提供,
编写函数调用
*-运算符将参数从列表或元组中解压出来:

>>> range(3, 6)             # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> range(*args)            # call with arguments unpacked from a list
[3, 4, 5]

以同样的方式,字典可以
传递关键字参数
**-运算符:

>>> def parrot(voltage, state='a stiff', action='voom'):
...     print "-- This parrot wouldn't", action,
...     print "if you put", voltage, "volts through it.",
...     print "E's", state, "!"
...
>>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
>>> parrot(**d)
-- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !

From the Python documentation:

The reverse situation occurs when the
arguments are already in a list or
tuple but need to be unpacked for a
function call requiring separate
positional arguments. For instance,
the built-in range() function expects
separate start and stop arguments. If
they are not available separately,
write the function call with the
*-operator to unpack the arguments out of a list or tuple:

>>> range(3, 6)             # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> range(*args)            # call with arguments unpacked from a list
[3, 4, 5]

In the same fashion, dictionaries can
deliver keyword arguments with the
**-operator:

>>> def parrot(voltage, state='a stiff', action='voom'):
...     print "-- This parrot wouldn't", action,
...     print "if you put", voltage, "volts through it.",
...     print "E's", state, "!"
...
>>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
>>> parrot(**d)
-- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文