如何修复mathematica中的列表分配
我想在 Mathematica 中执行以下操作
Table[p[i], {i, -3, 0}] = Flatten[{Table[0, {i, -3, -1}], 1}]
,但出现错误:
Set::write: Tag Table in Table[p[i], {i, -3, 0}] is Protected.
但是,这样做完全没问题:
{p[-3], p[-2], p[-1], p[0]} = Flatten[{Table[0, {i, -3, -1}], 1}]
非常感谢!
I want to do the following in Mathematica
Table[p[i], {i, -3, 0}] = Flatten[{Table[0, {i, -3, -1}], 1}]
But I got an error:
Set::write: Tag Table in Table[p[i], {i, -3, 0}] is Protected.
However, it is perfectly fine to do:
{p[-3], p[-2], p[-1], p[0]} = Flatten[{Table[0, {i, -3, -1}], 1}]
Many thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
强制 LHS 评估为可分配给的片段:
Evaluate[Table[p[i], {i, -3, 0}]] = Flatten[{Table[0, {i, -3, -1}] , 1}]
Force the LHS to evaluate into pieces that can be assigned to:
Evaluate[Table[p[i], {i, -3, 0}]] = Flatten[{Table[0, {i, -3, -1}], 1}]
它不起作用的原因是
Set
具有属性HoldFirst
。这意味着Set[a,stuff]
将符号a
而不是a
的值传递给Set
函数。至于为什么它有这个属性,问问自己:当你执行Set[a,stuff]
时,你是否要将stuff
赋值给符号a
>,或者a
的值?在您的示例中,
a
保存一个变量名称表,因此您需要a
的值,而HoldFirst
很烦人。但是,大多数时候a
的值类似于5
,并且您希望a=stuff
分配stuff
到符号a
,而不是值5
绕过 Holding 属性的常见模式如下:
The reason it doesn't work is because
Set
has attributeHoldFirst
. It means thatSet[a,stuff]
passes symbola
instead of value ofa
toSet
function. As to why it has this attribute, ask yourself: when you doSet[a,stuff]
, do you want to assignstuff
to symbola
, or to the value ofa
?In your example,
a
holds a table of variable names, so you want the value ofa
andHoldFirst
is annoying. However, most of the timea
will have a value like5
and you wanta=stuff
to assignstuff
to symbola
, not to the value5
A common pattern to get around Holding attributes is the following: