我有一个由元组组成的列表,我想将每个元组的元素作为参数传递给函数:
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)]
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
要明确@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.