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 に答える