4
$\begingroup$

Lets say I have 4 rows in

alist = {{1, 1, 3, 3, 1, 6}, {1, 1, 3, 4, 1, 1, x}, {1, 2, 3, 3, 1, 
    6}, {1, 2, 3, 4, 1, 1, x}};

If I want to select and print out only the rows with the "x" from the previous one, i.e.,

{{1, 1, 3, 4, 1, 1, x}, {1, 2, 3, 4, 1, 1, x}}

Is there a way to do it?

$\endgroup$
1
  • 1
    $\begingroup$ Thank for clarify the question @Syed $\endgroup$
    – kompaui
    Commented May 21, 2022 at 5:31

4 Answers 4

6
$\begingroup$

Using Select:

Select[alist, MemberQ[#, x] &]

Using Pick:

Pick[alist, MemberQ[#, x] & /@ alist]

Using Cases:

Cases[alist, {p___, x, q___}]

Using ContainsAny

Pick[alist, ContainsAny[#, {x}] & /@ alist]

or

Select[ContainsAny[{x}]][alist]

Result:

{{1, 1, 3, 4, 1, 1, x}, {1, 2, 3, 4, 1, 1, x}}
$\endgroup$
2
  • $\begingroup$ This is perfect!!!! Now I can adjust a little bit and get what I want. Thank you very much. $\endgroup$
    – kompaui
    Commented May 21, 2022 at 5:42
  • $\begingroup$ Thanks for the accept. I removed Tableform as you can apply it later to the results. Try to use *Form wrappers in general for display purposes only and not during computation. $\endgroup$
    – Syed
    Commented May 21, 2022 at 5:44
3
$\begingroup$
Select[alist,EqualTo[x]@*Last]
$\endgroup$
2
$\begingroup$
list = 
  {{1, 1, 3, 3, 1, 6}, 
   {1, 1, 3, 4, 1, 1, x},
   {1, 2, 3, 3, 1, 6}, 
   {1, 2, 3, 4, 1, 1, x}};

Using ReplaceAll

list /. {__?NumberQ} :> Nothing

{{1, 1, 3, 4, 1, 1, x}, {1, 2, 3, 4, 1, 1, x}}

Using SequenceSplit (new in 11.3)

Catenate @ SequenceSplit[list, {{__, _?NumberQ}}]

{{1, 1, 3, 4, 1, 1, x}, {1, 2, 3, 4, 1, 1, x}}

$\endgroup$
1
$\begingroup$
 list = 
  {{1, 1, 3, 3, 1, 6}, 
   {1, 1, 3, 4, 1, 1, x},
   {1, 2, 3, 3, 1, 6}, 
   {1, 2, 3, 4, 1, 1, x}};

Using DeleteCases:

DeleteCases[list, {__?NumericQ}]

{{1, 1, 3, 4, 1, 1, x}, {1, 2, 3, 4, 1, 1, x}}

Or using Replace at level 1:

Replace[list, {a__?NumericQ} :> Nothing, {1}]

{{1, 1, 3, 4, 1, 1, x}, {1, 2, 3, 4, 1, 1, x}}

Or using ReplaceList:

ReplaceList[list, {___, s : {p___, x, q___}, ___} :> s]

{{1, 1, 3, 4, 1, 1, x}, {1, 2, 3, 4, 1, 1, x}}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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