Services & Resources / Wolfram Forums
-----
 /
MathGroup Archive
2004
*January
*February
*March
*April
*May
*June
*July
*August
*September
*October
*November
*December
*Archive Index
*Ask about this page
*Print this page
*Give us feedback
*Sign up for the Wolfram Insider

MathGroup Archive 2004

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Selecting by first element of each list

  • To: mathgroup at smc.vnet.net
  • Subject: [mg48159] Re: Selecting by first element of each list
  • From: "Curt Fischer" <crf3 at po.cwru.edu>
  • Date: Fri, 14 May 2004 20:59:19 -0400 (EDT)
  • References: <c81i3m$509$1@smc.vnet.net>
  • Sender: owner-wri-mathgroup at wolfram.com

You could do this by using Sort[] and Split[].  The only thing is, you're
interested in sorting based off of the first element only, and interested in
partitioning the list based of the first element only.  So you have to
supply your own sorting and splitting rules to these functions, particularly
for Sort[].

In[1]:=
myList={{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}}

Out[1]=
{{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}}

In[2]:=
mySortedList=Sort[myList,OrderedQ[{#1[[1]], #2[[1]]}]&]

Out[2]=
{{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}}

In[3]:=
Split[mySortedList,_?(#1[[1]]===#2[[1]]&)]

Out[3]=
{{{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}}}

-- 
Curt Fischer



camartin at snet.net wrote:
> 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


  • Prev by Date: Re: Problems with Latex (Windows) and Mathematica 5.0
  • Next by Date: Re: Selecting by first element of each list
  • Previous by thread: RE: Selecting by first element of each list
  • Next by thread: Re: Selecting by first element of each list