如何将元组元素作为参数传递给函数? [英] How do I pass tuples elements to a function as arguments?

查看:42
本文介绍了如何将元组元素作为参数传递给函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个由元组组成的列表,我想将每个元组的元素作为参数传递给函数:

mylist = [(a, b), (c, d), (e, f)]myfunc(a, b)myfunc(c, d)myfunc(e, f)

我该怎么做?

解决方案

这实际上在 Python 中很简单,只需循环遍历列表并使用 splat 运算符 (*) 将其解包元组作为函数的参数:

mylist = [(a, b), (c, d), (e, f)]对于 mylist 中的 args:myfunc(*args)

例如:

<预><代码>>>>数字 = [(1, 2), (3, 4), (5, 6)]>>>对于数字中的参数:...打印(*参数)...1 23 45 6

I have a list consisting of tuples, I want to pass each tuple's elements to a function as arguments:

mylist = [(a, b), (c, d), (e, f)]

myfunc(a, b)
myfunc(c, d)
myfunc(e, f)

How do I do it?

解决方案

This is actually very simple to do in Python, simply loop over the list and use the splat operator (*) to unpack the tuple as arguments for the function:

mylist = [(a, b), (c, d), (e, f)]
for args in mylist:
    myfunc(*args)

E.g:

>>> numbers = [(1, 2), (3, 4), (5, 6)]
>>> for args in numbers:
...     print(*args)
... 
1 2
3 4
5 6

这篇关于如何将元组元素作为参数传递给函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆