|
[Date Index]
[Thread Index]
[Author Index]
Re: finding positions of elements in a list
- To: mathgroup at smc.vnet.net
- Subject: [mg86876] Re: finding positions of elements in a list
- From: "Dana DeLouis" <dana.del at gmail.com>
- Date: Tue, 25 Mar 2008 01:14:17 -0500 (EST)
"Szabolcs Horv=E1t" <szhorvat at gmail.com> wrote in message
news:fs7ikt$gk8$1 at 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.
Yes. Good point. As another example, to avoid errors with the following
method, one should set Heads -> False.
pts = {{20, 109}, {21, 50}, {20, 110}, {22, 60}};
Position[pts, v_ /; Last[v] > 80, 1, Heads -> False]
{{1}, {3}}
Extract[pts, %]
{{20, 109}, {20, 110}}
Prev by Date:
Re: Mathlink: How do I pass arbitrary data from Mathematica to C?
Next by Date:
Re: choose elements from list based on elements in different list
Previous by thread:
Re: finding positions of elements in a list
Next by thread:
Re: finding positions of elements in a list
|