问题
I have an expression which involves x1,x2,...,x100, I also have a list lst
with 100 elements, how to apply the rule to this expression to achieve something like the following:
exp/.{x1->lst[[1]],x2->lst[[2]],...,x100->lst[[100]]}
Thanks!
回答1:
exp /. Table[Symbol["x" <> ToString[i]] -> lst[[i]], {i, 1, 100}]
So you don't need to write X1,X2, ... X100
回答2:
You can use Thread
to apply the rules to each pair of expressions:
Thread[{a, b, c} -> {1, 2, 3}]
回答3:
It is much simpler and more convenient to solve such tasks using indexed variables instead of generation of a list of different Symbol
s. In this way:
listOfRules = Array[f@# :> list[[#]] &, {100}];
Short@%
=> {f[1]:>list[[1]],f[2]:>list[[2]],f[3]:>list[[3]],f[4]:>list[[4]],
<<92>>,f[97]:>list[[97]],f[98]:>list[[98]],f[99]:>list[[99]],f[100]:>list[[100]]}
If you plan to make such replacement many times, it is worth to Dispatch
large list of rules:
listOfRules = Dispatch@listOfRules;
The replacement can be made as usual:
expr /. listOfRules
来源:https://stackoverflow.com/questions/4743121/how-to-apply-a-rule-involving-a-hundred-variables-in-mathematica