问题
How would I go about applying each element in a list to each argument in a function? Kind of like Map, except with a variable number of arguments.
So for example, if I have a function action[x1_,x2_,x3_]:=..., and I have a list {1,2,3}, how would I create a function to call action with action[1,2,3]?
I would like this function be able to handle me changing action to action[x1_,x2], and anything else, also, with the list now being {1,2}, and to call action now with action[1,2].
回答1:
Based on "Kind of like Map, except with a variable number of arguments." I think you might be looking for Apply to level 1. This is done with:
Apply[function, array, {1}]
or the shorthand:
function @@@ array
Here is what it does:
array = {{1, 2, 3}, {a, b, c}, {Pi, Sin, Tan}};
action @@@ array
{action[1, 2, 3], action[a, b, c], action[Pi, Sin, Tan]}
The terminology I used above could be misleading, and limits the power of Apply. The expression to which you apply action does not need to be a rectangular array. It does not even need to be a List: {...} or have its elements be lists. Here is an example incorporating these possibilities:
args = {1, 2} | f[a, b, c] | {Pi};
action @@@ args
action[1, 2] | action[a, b, c] | action[Pi]
argsis not aListbut a set ofAlternatives- the number of arguments passed to
actionvaries - one of the elements of
argshas headf
Observe that:
actionreplaces the head of each element ofargs, whatever it may be.- The head of
argsis preserved in the output, in this caseAlternatives(short form:a | b | c)
回答2:
Apply[action, {1,2,3}]
This also can be entered as action @@ {1,2,3}.
回答3:
Why not just use action[lst_?ListQ]?
来源:https://stackoverflow.com/questions/5746717/apply-list-to-arguments-in-mathematica