如何为符号设置值 [英] How to set values to symbols
问题描述
我想将值设置为变量列表,如下所示:
I would like to set values to a list of variables, like so:
list[[1]] = 2
如果 list[[1]]
是 a
,那么 a
现在将等于 2.我怎样才能做到这一点?
and if list[[1]]
is a
, then a
will now be equal to two. How can I achieve this?
推荐答案
好吧,让我们天真地尝试一下:
Well, let's try it naively:
列个清单:
In[1]:= ClearAll[list, a, b, c];
list = {a, b, c};
正如我们所料:
In[3]:= list
Out[3]= {a, b, c}
将第一个元素设置为 2:
Set the first element to 2:
In[4]:= list[[1]] = 2
Out[4]= 2
In[5]:= list
Out[5]= {2, b, c}
这不会影响一个:
In[6]:= a
Out[6]= a
重新开始:
In[7]:= ClearAll[list, a, b, c];
list = {a, b, c};
In[9]:= list
Out[9]= {a, b, c}
问题在于 Set (=) 将 HoldFirst
作为其属性之一,即,它不评估其左侧的第一个参数,并且分配给列表和而不是那个位置的变量.但是您可以使用 Evaluate
强制评估:
The problem is that Set (=) has HoldFirst
as one of its attributes , i.e., it doesn't evaluate its first argument which is the lefthand side, and the assignment is to the list and not to the variable that's in that location. But you can force evaluation using Evaluate
:
In[10]:= Evaluate[list[[1]]] = 2
Out[10]= 2
现在列表似乎和以前一样:
Now the list seems to be the same as before:
In[11]:= list
Out[11]= {2, b, c}
但这只是因为 a 仍然存在并且得到了 2 的值(在以前的版本中 a 被 替换 为 2):
but that's only because a is still there and has gotten the value of 2 (in the previous version a was replaced by 2):
In[12]:= a
Out[12]= 2
如果您现在将 a 设置为 3,您也会看到该更改列表:
If you now set a to 3 you'll see that that changes list too:
In[13]:= a = 3
Out[13]= 3
In[14]:= list
Out[14]= {3, b, c}
<小时>
编辑
也许更接近您的问题的措辞,您可以在列表上Map
Set
:
Perhaps more close to the wording of your question, you could Map
Set
over the list:
In[16]:= ClearAll[list, a, b, c];
list = {a, b, c};
In[18]:= Set[#, RandomInteger[10]] & /@ list
Out[18]= {4, 8, 1}
In[19]:= list
Out[19]= {4, 8, 1}
In[21]:= {a, b, c}
Out[21]= {4, 8, 1}
这篇关于如何为符号设置值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!