3
$\begingroup$

How we can remove all pairs {x,y} of a list which begin from a special x.

For example:

list={{1,2},{4,5},{5,9},{8,13},{9,0.1},{15,-0.2},{17,-9},{23,2}};

We want keep pairs in which x=<9:

extractlist={{1,2},{4,5},{5,9},{8,13},{9,0.1}};

$\endgroup$
1
  • $\begingroup$ If the x's are ordered (as coolwater points out), then TakeWhile[list, #[[1]] <= 9 &] may be (yet another) option worth considering. $\endgroup$
    – user1066
    Dec 26, 2017 at 0:08

5 Answers 5

6
$\begingroup$
list = {{1, 2}, {4, 5}, {5, 9}, {8, 13}, {9, 0.1}, {15, -0.2}, {17, -9}, {23, 
    2}};

trimmedList = Select[list, #[[1]] <= 9 &]

(* {{1, 2}, {4, 5}, {5, 9}, {8, 13}, {9, 0.1}} *)

Some other ways

trimmedList ==
 Cases[list, _?(#[[1]] <= 9 &)] ==
 Cases[list, {_?(# <= 9 &), _}] ==
 DeleteCases[list, _?(#[[1]] > 9 &)] ==
 DeleteCases[list, {_?(# > 9 &), _}]

(* True *)
$\endgroup$
6
$\begingroup$

I think:

extractlist=DeleteCases[list, {x_, y_} /; x > 9]

does the job.

$\endgroup$
6
$\begingroup$
Select[list, #[[1]] <= 9 &]

Select is a reasonably simple method.

$\endgroup$
3
$\begingroup$

If the xs are ordered in list

list[[;; Last[Ordering[Ordering[Append[list[[-1 ;; 1 ;; -1, 1]], 9.]]]] - 1]]
{{1, 2}, {4, 5}, {5, 9}, {8, 13}, {9, 0.1}}

Otherwise

Pick[list, Clip[list[[All, 1]], {9., 9.}, {9., 0}], 9.]
{{1, 2}, {4, 5}, {5, 9}, {8, 13}, {9, 0.1}}
$\endgroup$
1
  • 1
    $\begingroup$ The one involving Ordering is especially appealing. +1 $\endgroup$
    – Rabbit
    Dec 23, 2017 at 21:48
2
$\begingroup$
list = {{1, 2}, {4, 5}, {5, 9}, {8, 13}, {9, 0.1},
{15, -0.2}, {17, -9}, {23, 2}} /. {x_, _} /; x > 9 -> Sequence[]
$\endgroup$

Not the answer you're looking for? Browse other questions tagged or ask your own question.