Re: List Operations
- To: mathgroup at smc.vnet.net
- Subject: [mg65710] Re: [mg65681] List Operations
- From: Andrzej Kozlowski <akoz at mimuw.edu.pl>
- Date: Sun, 16 Apr 2006 01:45:17 -0400 (EDT)
- References: <200604140832.EAA22085@smc.vnet.net> <6921F99C-AC55-4966-B588-F29487922B0D@mimuw.edu.pl> <FA248633-57A1-4440-81B7-AB73A59A8AE6@mimuw.edu.pl>
- Sender: owner-wri-mathgroup at wolfram.com
On 15 Apr 2006, at 16:54, Andrzej Kozlowski wrote: > > On 15 Apr 2006, at 10:10, Andrzej Kozlowski wrote: > >> >> On 14 Apr 2006, at 17:32, LectorZ wrote: >> >>> Hi guys, >>> >>> My question: >>> >>> mylist={{1,a, b},{1,a, b},{1,a, >>> b},{2,b,z},{2,b,z},{2,b,z},{2,b,z},....,{n,x,y},{n,x,y}, >>> {n,x,y},...{n,x,y}} >>> >>> The sublists are of different length. >>> >>> I need to calculate the product between the 2nd and 3rd element of >>> every sublist (e.g. a*b) and then add them up according to the 1st >>> element: sum of all products where the 1st element is 1, 2, ...n. >>> >>> The result should be a list like that: >>> {{1,a*b+a*b+a*b},{2,b*z+b*z+b*z+b*z}, ...,{n, x*y+x*y+x*y+...+x*y}} >>> >>> Thank you for your help. >>> >>> LZ >>> >> >> It is impossible in Mathematica to get Mathematica to output >> something in the form a+a+a and the like instead of 3a , without >> using HoldForm. So, you should either use something like this: >> >> mylist = {{1, a, b}, {1, a, b}, {1, a, >> b}, {2, b, z}, {2, b, z}, {2, b, z}, {2, b, z}}; >> >> >> >> mylist /. {i_, x_, y_} -> {i, x*y} //. {a___, {i_, x_}, {i_, y_}, >> b___} -> {a, {i, x + y}, b} >> >> {{1, 3*a*b}, {2, 4*b*z}} >> >> or if you really want it to look as you wrote it: >> >> >> SetAttributes[plus,{Flat,OneIdentity}] >> >> >> Format[plus[x___]]:=HoldForm[Plus[x]] >> >> >> mylist /. {i_, x_, y_} -> {i, x*y} //. {a___, {i_, x_}, {i_, y_}, >> b___} -> {a, {i, HoldForm[x + y]}, b} >> >> >> {{1,a*b+a*b+a*b},{2,b z+b*z+b*z+b*z}} >> >> Andrzej Kozlowski >> > > > Sorry, I copied and pasted not what I intended. The second example > should have been: > > > SetAttributes[plus,{Flat,OneIdentity}]; > > Format[plus[x___]]:=HoldForm[Plus[x]]; > > Split[mylist /. {i_, x_, y_} -> {i, x*y}, #1[[1]] == #2[[1]] > & ] //. {a___, {i_, x_}, {i_, y_}, b___} -> > {a, {i, plus[x, y]}, b} > > > {{{1, a*b + a*b + a*b}}, {{2, b*z + b*z + b*z + b*z}}} > > > > Another silly mistake: there is no need for Split in the above. This will do just as well: SetAttributes[plus,{Flat,OneIdentity}]; Format[plus[x___]]:=HoldForm[Plus[x]]; mylist /. {i_, x_, y_} -> {i, x*y} //. {a___, {i_, x_}, {i_, y_}, b___} -> {a, {i, plus[x, y]}, b} Andrzej Kozlowski
- References:
- List Operations
- From: "LectorZ" <lectorz@mail.ru>
- List Operations