私は、Pythonに関数があるのだろうか-今それを呼び出しましょうapply
-それは次のことを行います:
apply(f_1, 1) = f_1(1)
apply(f_2, (1, 2)) = f_1(1, 2)
...
apply(f_n, (1, 2,..., n)) = f_n(1, 2,..., n) # works with a tuple of proper length
それは例えば存在するので。A+とMathematicaは、以前は本当に役に立ちました。乾杯!
私は、Pythonに関数があるのだろうか-今それを呼び出しましょうapply
-それは次のことを行います:
apply(f_1, 1) = f_1(1)
apply(f_2, (1, 2)) = f_1(1, 2)
...
apply(f_n, (1, 2,..., n)) = f_n(1, 2,..., n) # works with a tuple of proper length
それは例えば存在するので。A+とMathematicaは、以前は本当に役に立ちました。乾杯!
*
演算子を使用して同じ効果を得ることができます。
f_1(*(1, 2)) = f_1(1, 2)
...
次の式*
はタプルである必要はなく、シーケンスに評価される任意の式にすることができます。
Python には、期待どおりの機能を実行する組み込みapply
関数もありますが*
、Python 2.3 以降、演算子が優先されて廃止されました。apply
何らかの理由で必要であり、非推奨の汚染を避けたい場合は、実装するのは簡単です:
def my_apply(f, args):
return f(*args)
Python には、「引数アンパッキング」または単に「splat」と呼ばれる言語レベルの機能があります。
# With positional arguments
args = (1, 2, 3)
f_1(*args)
# With keyword arguments
kwargs = {'first': 1, 'second': 2}
f_2(**kwargs)
はい、*
引数のリストで演算子を使用します。実際の例:
max(1, 2, 3, 4, 5) # normal invocation
=> 5
max(*[1, 2, 3, 4, 5]) # apply-like invocation
=> 5
2 番目のスニペットは、apply(max, [1, 2, 3, 4, 5])