Message Boards Message Boards

0
|
555 Views
|
7 Replies
|
1 Total Likes
View groups...
Share
Share this post:

Perform a pattern match only on the first element in sublist

Posted 1 month ago

I have the following list:

data=
{
 {0, 106},
 {1, 120},
 {2, 116},
 {3, 114},
 {4, 130},
 {5, 109}
 }

I want to find the positions of the elements in data that their first element (you might call it the first column) is larger than 2. So in this example the positions I am looking for are the last three:

{{4},{5},{6}}

The following, which makes use of levelspec, doesn't give a correct result:

Position[data, x_ /; x > 2, {2}]
(*{{1, 2}, {2, 2}, {3, 2}, {4, 2}, {5, 2}, {6, 2}, {7, 2}, {8, 2}, {9, 1}, {9, 2}, {10, 1}, {10, 2}, {11, 1}, {11, 2}}*)

Any idea how to perform this check?

POSTED BY: Ehud Behar
7 Replies

You can use pattern Condition on couples:

Position[data, {x_ /; x > 2, _}]
POSTED BY: Gianluca Gorni
Posted 1 month ago

Deleted

POSTED BY: Hans Milton
Posted 1 month ago

One way:

Position[data, {x_?(GreaterThan[2]), _}]
POSTED BY: Eric Rimbey
Posted 1 month ago

Clever.

Is there a way to perform this check (whether the number is greater than 2 or not) using a pure function? I.e., don't use an argument explicit name such as x in my example.

POSTED BY: Ehud Behar
Posted 1 month ago

Eric's pattern works also without naming the first blank:

Position[data, {_?(GreaterThan[2]), _}]

With a pure function:

Position[data, {_?(# > 2 &), _}]
POSTED BY: Hans Milton
Posted 1 month ago

As Hans pointed out, the x is superfluous. The GreaterThan[2] is a pure function. Are you asking whether we could shed even more of the pattern? Maybe something like:

Position[data, _?(GreaterThan[2]@*First), {1}, Heads -> False]

(The trailing options aren't strictly necessary, but they help avoid error messages.)

I often find the mixing of pattern and filter function less than pleasing aesthetically--I'm not sure why. But you might also consider something like:

PositionIndex[GreaterThan[2]@*First /@ data]
(* <|False -> {1, 2, 3}, True -> {4, 5, 6}|> *)

PositionIndex[GreaterThan[2]@*First /@ data][True]
(* {4, 5, 6} *)

Obviously the semantics are a bit different (position/extract versus index/part), so it depends on how you need to use the results.

POSTED BY: Eric Rimbey
Posted 1 month ago

Thanks A LOT for your answer.

POSTED BY: Ehud Behar
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract