14

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

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

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

我该怎么做?

4

2 回答 2

28

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

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

例如:

>>> numbers = [(1, 2), (3, 4), (5, 6)]
>>> for args in numbers:
...     print(*args)
... 
1 2
3 4
5 6
于 2012-05-16T19:19:39.627 回答
1

要明确@DSM 的评论:

>>> from itertools import starmap
>>> list(starmap(print, ((1,2), (3,4), (5,6)))) 
# 'list' is used here to force the generator to run out.
# You could instead just iterate like `for _ in starmap(...): pass`, etc.
1 2
3 4
5 6
[None, None, None] # the actual created list;
# `print` returns `None` after printing.
于 2012-05-16T20:06:28.297 回答