将列表应用于 Mathematica 中的参数 [英] Apply list to arguments in Mathematica
问题描述
我将如何将列表中的每个元素应用于函数中的每个参数?有点像 Map
,只是参数数量可变.
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.
例如,如果我有一个函数 action[x1_,x2_,x3_]:=...
,并且我有一个列表 {1,2,3}
,我将如何创建一个函数来调用 action
和 action[1,2,3]
?
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]
?
我希望这个函数能够处理我将 action
更改为 action[x1_,x2]
以及其他任何内容,并且列表现在是 {1,2}
,并立即使用 action[1,2]
调用操作.
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]
.
推荐答案
基于有点像 Map,但参数数量可变."我想您可能正在寻找 Apply
到级别 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}]
或简写:
function @@@ array
这是它的作用:
array = {{1, 2, 3}, {a, b, c}, {Pi, Sin, Tan}};
action @@@ array
{action[1, 2, 3], action[a, b, c], action[Pi, Sin, Tan]}
<小时>
我在上面使用的术语可能会产生误导,并限制了 Apply
的力量.您应用 action
的表达式不需要是矩形数组.它甚至不需要是一个 List
: {...}
或者它的元素是列表.以下是包含这些可能性的示例:
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]
args
不是List
而是一组Alternatives
- 传递给
action
的参数数量不同 args
的元素之一有头部f
args
is not aList
but a set ofAlternatives
- the number of arguments passed to
action
varies - one of the elements of
args
has headf
action
替换args
的每个元素的头部,无论它是什么.args
的头部保留在输出中,在本例中为Alternatives
(缩写:a | b | c
)立>action
replaces the head of each element ofargs
, whatever it may be.- The head of
args
is preserved in the output, in this caseAlternatives
(short form:a | b | c
)
注意:
这篇关于将列表应用于 Mathematica 中的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!