Re: Selecting by first element of each list
- To: mathgroup at smc.vnet.net
- Subject: [mg48151] Re: [mg48130] Selecting by first element of each list
- From: Tomas Garza <tgarza01 at prodigy.net.mx>
- Date: Fri, 14 May 2004 20:59:07 -0400 (EDT)
- References: <200405140412.AAA04773@smc.vnet.net>
- Sender: owner-wri-mathgroup at wolfram.com
You may use Split with a test. This is your list, which you wish to have grouped by the first element. In[1]:= theList = {{2, 3, 4, 5, 77}, {2, 4, 5, 66, 77}, {3, 4, 7, 8, 90, 6}, {3, 5, 6, 7, 8, 0}, {3, 45, 67, 77, 12}}; First, use a Sort so that all sublists with equal first element are adjacent (in your example they already are): In[2]:= sortedList = Sort[theList] Out[2]= {{2, 3, 4, 5, 77}, {2, 4, 5, 66, 77}, {3, 45, 67, 77, 12}, {3, 4, 7, 8, 90, 6}, {3, 5, 6, 7, 8, 0}} Then use Split on sortedList with the test requiring that two adjacent sublists with the same first element remain in the same set. In[3]:= Split[sortedList, #1[[1]] == #2[[1]] & ] Out[3]= {{{2, 3, 4, 5, 77}, {2, 4, 5, 66, 77}}, {{3, 45, 67, 77, 12}, {3, 4, 7, 8, 90, 6}, {3, 5, 6, 7, 8, 0}}} You would benefit from looking at Split in the Help browser. You'll find there a couple of very illustrative and useful examples. Tomas Garza Mexico City ----- Original Message ----- From: <camartin at snet.net> To: mathgroup at smc.vnet.net Subject: [mg48151] [mg48130] Selecting by first element of each list > Hi, > > I'm trying to learn to handle a flat file kind of database using > Mathematica. An example is the list of lists below: > > {{2,3,4,5,77},{2,4,5,66,77},{3,4,7,8,90,6},{3,5,6,7,8,0},{3,45,67,77,12}} > > It's actually more complicated than this but good enough for > illustrative purposes. The first element in each list is actually an > identifier, like an account number. I want to create a list of lists > with each account, that is, > > {{{2,3,4,5,77},{2,4,5,66,77}}, > {{3,4,7,8,90,6},{3,5,6,7,8,0},{3,45,67,77,12}}}. > > When I use Select with an anonymous function such as > > Select[list1,#1[[1]] = = #2[[1]]&] > > I get an error because it stops (of course) after the first two lists. I > get the right grouping for the first list but it doesn't finish. I don't > understand how to use the anonymous function to go through my list (it's > got several thousand entries) and select and group by the first element > in each group. I've been through the archive but nothing there quite helps. > > I would appreciate some direction. > > Thanks > > Cliff > > >
- References:
- Selecting by first element of each list
- From: "camartin@snet.net" <camartin@snet.net>
- Selecting by first element of each list