0
$\begingroup$

Imagine I have a list of the type

Lst = {{1,0,1,1},{4,0,1,1}, {1,1,0,0},{2,1,1,1},{0,0,0,1}}

I want to select only those sublists that only contain elements 0 or 1. For example for the above list the reduced list which I want is

IWantThis = {{1,0,1,1},{1,1,0,0},{0,0,0,1}}

Motivation for this is the given situation describes spinless fermions or spin 1/2 objects.

$\endgroup$
  • $\begingroup$ If the order doesn't matter then BitAnd[Lst, 1] ⋂ Lst does it $\endgroup$ – Coolwater Feb 27 at 12:21
3
$\begingroup$

To filter a list

list = {{1, 0, 1, 1}, {4, 0, 1, 1}, {1, 1, 0, 0}, {2, 1, 1, 1}, {0, 0, 0, 1}};

you can use Select like this:

Select[list, ContainsOnly[{0, 1}]]
(* {{1, 0, 1, 1}, {1, 1, 0, 0}, {0, 0, 0, 1}} *)

This should work with Mathematica 10.2+.

$\endgroup$
  • $\begingroup$ OK. Thanks a lot $\endgroup$ – Quasar Supernova Feb 27 at 11:50
  • 1
    $\begingroup$ In earlier versions, use Cases[] instead: Cases[list, {(0 | 1) ..}]. $\endgroup$ – J. M. is away Mar 1 at 9:30
2
$\begingroup$

Using Select and Union.

Lst = {{1,0,1,1},{4,0,1,1}, {1,1,0,0},{2,1,1,1},{0,0,0,1}};
Select[Lst, Union[#] == {0, 1} &]

{{1,0,1,1},{1,1,0,0},{0,0,0,1}}

I have used Unionspecifically, because it sorts out the list after removing duplicates unlike DeleteDuplicates.

$\endgroup$
  • $\begingroup$ Ok thanks a lot $\endgroup$ – Quasar Supernova Feb 27 at 11:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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