Mathematica Asked by Boogeyman on January 19, 2021
I have the following list :
list={a^2, b^2, a^-1, a^2+b^2, (a+b+c)^-1, (a+b-c)^-2}
Do[Print[list[[i]]//FullForm],{i,1,Length[list]}]
I want to break this list into two lists: one containing elements starting with Power
and another starting with Plus
. In this case it will be
list1 = {a^2, b^2, a^-1, (a+b+c)^-1, (a+b-c)^-2}
list2 = {a^2+b^2}
A priori the position of elements starting with Power
or Plus
is not fixed and also the elements could be complicated. Is it possible to do this?
list = {a^2, b^2, a^-1, a^2+b^2, (a+b+c)^-1, (a+b-c)^-2};
{list1, list2} = GatherBy[list, Head]
(* Out:
{
{a^2, b^2, a^(-1), (a + b + c)^(-1), (a + b - c)^(-2)},
{a^2 + b^2}
}
*)
If you want to specify in which order the heads should be extracted, then you could use multiple Cases statements:
{powerList, plusList} = Cases[list, Blank[#]]& /@ {Power, Plus}
(* Out:
{
{a^2, b^2, 1/a, 1/(a + b + c), 1/(a + b - c)^2},
{a^2 + b^2}}
}
*)
Answered by MarcoB on January 19, 2021
{l1, l2} = Function[x, Select[#, #[[0]] === x &]]&[list]/@{Power, Plus}
Alternatively, using Pick
:
{lone,ltwo} = Pick[#1, #1[[All,0]], #2]&[list,#]&/@{Power, Plus}
l1
l2
$$ left{a^2,b^2,frac{1}{a},frac{1}{a+b+c},frac{1}{(a+b-c)^2}right} $$
$$ left{a^2+b^2right} $$
Answered by user1066 on January 19, 2021
Cases do the job.
{a^2, b^2, a^-1, a^2 + b^2, (a + b + c)^-1, (a + b - c)^-2} // {Cases[_Power]@#, Cases[_Plus]@#} &
Answered by wuyudi on January 19, 2021
grouped = GroupBy[list, Head]
<|Power -> {a^2, b^2, 1/a, 1/(a + b + c), 1/(a + b - c)^2}, Plus -> {a^2 + b^2}|>
grouped /@ {Power, Plus}
{{a^2, b^2, 1/a, 1/(a + b + c), 1/(a + b - c)^2}, {a^2 + b^2}}
Lookup[{Plus, Power}] @ grouped
{{a^2 + b^2}, {a^2, b^2, 1/a, 1/(a + b + c), 1/(a + b - c)^2}}
KeyTake[Plus] @ grouped
<|Plus -> {a^2 + b^2}|>
KeyDrop[Plus] @ grouped
<|Power -> {a^2, b^2, 1/a, 1/(a + b + c), 1/(a + b - c)^2}|>
Answered by kglr on January 19, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP