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$

marked as duplicate by Michael E2, m_goldberg, b3m2a1, Henrik Schumacher, Coolwater Dec 26 '17 at 19:21

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • $\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 '17 at 0:08
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$
Select[list, #[[1]] <= 9 &]

Select is a reasonably simple method.

$\endgroup$
5
$\begingroup$

I think:

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

does the job.

$\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
    $\begingroup$ The one involving Ordering is especially appealing. +1 $\endgroup$ – Rabbit Dec 23 '17 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.