Re: finding positions of elements in a list
- To: mathgroup at smc.vnet.net
- Subject: [mg86860] Re: finding positions of elements in a list
- From: Szabolcs Horvát <szhorvat at gmail.com>
- Date: Mon, 24 Mar 2008 01:43:19 -0500 (EST)
- Organization: University of Bergen
- References: <fs4rs5$p9h$1@smc.vnet.net>
Dana DeLouis wrote:
>> I also tried Position but it wasn't clear to me if a pattern can be used
> for this.
>
> Hi. You have answers, but I see you were stuck on using "Position."
> Here's one way if you ever need to use it:
>
>
> pts = {{20, 109}, {21, 50}, {20, 110}, {22, 60}};
>
> Position[pts, {___, n_} /; n > 80]
>
> {{1}, {3}}
>
> Extract[pts, %]
>
> {{20, 109}, {20, 110}}
There is one important caveat though, which is not present with Cases or
Select. Position[] searches the expression at all levels. Suppose that
we are trying to find those pairs whose second element is not 1.
In[1]:= pts = RandomInteger[2, {10, 2}]
Out[1]= {{1, 0}, {0, 0}, {2, 0}, {0, 2}, {2, 0}, {1, 2}, {2, 2},
{2, 1}, {1, 1}, {0, 1}}
In[2]:= Position[pts, {___, n_} /; n =!= 1]
Out[2]= {{1}, {2}, {3}, {4}, {5}, {6}, {7}, {}}
Note the {} at the end of the list. It indicates that the complete
expression matches too.
There are many little details that can hide this behaviour for most
input lists (e.g. using a different pattern or != instead of =!=), but
it is good to mention that it is possible to only match against the
elements of the list by using a level specification:
Position[pts, {___, n_}, {1}]
This might seem like a trivial detail, but I have been bitten by this
type of mistake more than once.