我有一个由元组组成的列表,我想将每个元组的元素作为参数传递给函数:
mylist = [(a, b), (c, d), (e, f)]
myfunc(a, b)
myfunc(c, d)
myfunc(e, f)
我该怎么做?
最好的问候
答案 0 :(得分:25)
这在Python中实际上非常简单,只需循环遍历列表并使用splat运算符(*
)将元组解压缩为函数的参数:
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
答案 1 :(得分: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.