タプルで構成されるリストがあり、各タプルの要素を引数として関数に渡したい:
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.