Re: Using Part
- To: mathgroup at smc.vnet.net
- Subject: [mg77079] Re: Using Part
- From: Jean-Marc Gulliet <jeanmarc.gulliet at gmail.com>
- Date: Sun, 3 Jun 2007 06:04:56 -0400 (EDT)
- Organization: The Open University, Milton Keynes, UK
- References: <f3r949$sqp$1@smc.vnet.net>
Clifford Martin wrote: > Group, > > I need some educational help. Below is a list of lists I'm trying to manipulate. Notice that the date is in the 6th place in each list. What I want to do is 1) identify the lists with identical dates and 2) once I've done that add the third element of each list with identical dates together and 3) eliminate the two original lists. > > {{{16871,I7,614,48876,850,{2006,12,2}},{16871,I7,538.3,49803,850,{2007,1,8}}, > {16871,I7,474.8,50655,850,{2007,2,1}},{16871,I7,428.1,51430,850,{2007,2,20}}, > {16871,I7,74.9,51430,850,{2007,2,20}},{16871,I7,535,52348,850,{2007,3,20}}, > {16871,I7,395.9,53383,850,{2007,5,9}}} > > So what I would end up with would be: > > {{{16871,I7,614,48876,850,{2006,12,2}},{16871,I7,538.3,49803,850,{2007,1,8}}, > {16871,I7,474.8,50655,850,{2007,2,1}},{16871,I7,503,51430,850,{2007,2,20}}, > {16871,I7,535,52348,850,{2007,3,20}},{16871,I7,395.9,53383,850,{2007,5,9}}} > > There is something about using Part that I'm not understanding. In the list below if I say: > Part[list,4,6]==Part[list,5,6] I get > True > > but if I try to find it with an anonymous function like > Select[list,Part[#1,6]==Part[#2,6] this doesn't find it. Clearly I'm not understanding how to use these functions with Part. I've tried many variations of this and it just shows I'm not understanding something fundamental. > > Thanks for your help in advance. > > Cliff Cliff, Indeed, the issue is not about your understanding of Part, but in the fact that Select deals with only one entry per test. Slot #2, therefore, has no meaning in this context. The following function should do what you want. In[1]:= lst = {{16871, I7, 614, 48876, 850, {2006, 12, 2}}, {16871, I7, 538.3, 49803, 850, {2007, 1, 8}}, {16871, I7, 474.8, 50655, 850, {2007, 2, 1}}, {16871, I7, 428.1, 51430, 850, {2007, 2, 20}}, {16871, I7, 74.9, 51430, 850, {2007, 2, 20}}, {16871, I7, 535, 52348, 850, {2007, 3, 20}}, {16871, I7, 395.9, 53383, 850, {2007, 5, 9}}}; myFun[lst_List] := Module[{s, tot}, s = Split[lst, #1[[6]] == #2[[6]] & ]; tot = (Total[#1[[All, 3]]] & ) /@ s; s = Flatten[(Union[#1, SameTest -> (#1[[6]] == #2[[6]] & )] & ) /@ s, 1]; s[[All, 3]] = tot; s] myFun[lst] Out[3]= {{16871, I7, 614, 48876, 850, {2006, 12, 2}}, {16871, I7, 538.3, 49803, 850, {2007, 1, 8}}, {16871, I7, 474.8, 50655, 850, {2007, 2, 1}}, {16871, I7, 503., 51430, 850, {2007, 2, 20}}, {16871, I7, 535, 52348, 850, {2007, 3, 20}}, {16871, I7, 395.9, 53383, 850, {2007, 5, 9}}} Regards, Jean-Marc