Group Abstract Group Abstract

Message Boards Message Boards

0
|
20.7K Views
|
8 Replies
|
10 Total Likes
View groups...
Share
Share this post:

Delete cases for a list of pairs of numbers?

Posted 9 years ago

I have a list of pairs of numbers, and I would like to remove all pairs for which the first element in the pair is below a specified value. For instance:

list = {{-2, 3}, {0, 3}, {2, 3}, {2, -1}, {-1, 1.2}}

Removing all pairs for which the first element in each pair is less than 1 would give:

{{2, 3}, {2, -1}}

How do I accomplish this? I assume Select or DeleteCases can be used. Something like

DeleteCases[{{-2, 3}, {0, 3}, {2, 3}, {2, -1}, {-1, 1.2}}, {LessThan[1],_}]

but that doesn't work. Thanks in advance.

POSTED BY: Bryan Lettner
8 Replies
Posted 9 years ago

For speed and simplicity, I am going with:

Select[list, First[#] > 0 && Last[#] <= 0.6 &]

(I didn't mention, but I also need to impose a condition on the second element of each list.)

POSTED BY: Bryan Lettner
Posted 9 years ago

You could also extend it to any partition size, for example sets of 3

list = Partition[RandomInteger[{-10, 10}, 160], 3]; AbsoluteTiming[
 Select[list, #[[1]] >= -1 && #[[2]] <= 2 && #[[3]] >= 1 &]]
POSTED BY: Paul Cleary
Posted 9 years ago

Or how about

list = {{-2, 3}, {0, 3}, {2, 3}, {2, -1}, {-1, 1.2}}


DeleteCases[list, {a_, b_} /; a < 1]

Select[list, First[#] > 1 &]
POSTED BY: Paul Cleary
Posted 9 years ago

Removing elements less than 1 implies select elements greater than or equal 1

list = {{-2, 3}, {0, 3}, {2, 3}, {2, -1}, {-1, 1.2}, {1, 5}};
Select[list, First[#] >= 1 &]
POSTED BY: Okkes Dulgerci
Posted 9 years ago

Yes indeed, however, I should have used >0. I have in the past had timing issues when using >= it seems to slow things down, not so in this case, but if at all possible I always try and use just a single element if possible.

POSTED BY: Paul Cleary

Alternatively one can do it like:

DeleteCases[{{-2, 3}, {0, 3}, {2, 3}, {2, -1}, {-1,1.2}}, {_?(LessThan[1]), _}]
Select[{{-2, 3}, {0, 3}, {2, 3}, {2, -1}, {-1, 1.2}}, !LessThan[1][First[#]] &]

I always tend to favour Select when a function has to be done, and Cases/DeleteCases when it is a 'pure simple pattern' (without Condition or PatternTest).

POSTED BY: Sander Huisman

One way might be

DeleteCases[list, x_ /; x[[1]] < 1]

which gives

{{2, 3}, {2, -1}}
POSTED BY: Nasser M. Abbasi
Posted 9 years ago

works perfect thank you!

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