6
$\begingroup$

There is a list:

{1, {a, b, c}, 1, {1, 2, 3, 4, 5, 6, 7, 8}, {A, B, D, Z}}

It contains sublists of different elements and several $1$s. The goal is to replace an element to $0$ if it's not $1$.

Desirable outcome:

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

I know that there is a replace all (/.) function that can do such work but can't find out how to apply it here. What can I do?

$\endgroup$

5 Answers 5

10
$\begingroup$
Replace[
 {1, {a, b, c}, 1, {1, 2, 3, 4, 5, 6, 7, 8}, {A, B, D, Z}},
 Except[1] :> 0,
 1
 ]

where the third argument of Replace contrains the application of the replacement rule to the 1st level of the expression.

$\endgroup$
3
$\begingroup$
list = {1, {a, b, c}, 1, {1, 2, 3, 4, 5, 6, 7, 8}, {A, B, D, Z}};

There will be lots of ways of doing this, but here is one.

If[# === 1, 1, 0] & /@ list
(* {1, 0, 1, 0, 0} *)

(Solving this using pattern matching is made more difficult by the need to avoid matching the whole list).

$\endgroup$
1
$\begingroup$
list = {1, {a, b, c}, 1, {1, 2, 3, 4, 5, 6, 7, 8}, {A, B, D, Z}};

Using SequenceSplit (new in 11.3)

Flatten @ SequenceSplit[list, {_List} :> 0]

{1, 0, 1, 0, 0}

Using ReplaceAt (new in 13.1)

ReplaceAt[_ :> 0, Position[list, _?VectorQ]] @ list

{1, 0, 1, 0, 0}

$\endgroup$
1
$\begingroup$
list = {1, {a, b, c}, 1, {1, 2, 3, 4, 5, 6, 7, 8}, {A, B, D, Z}};

Using ReplacePart:

ReplacePart[list, Position[list, x_List, 1] -> 0]

(*{1, 0, 1, 0, 0}*)
$\endgroup$
1
$\begingroup$
Clear["Global`"];
lis = {1, {a, b, c}, 1, {1, 2, 3, 4, 5, 6, 7, 8}, {A, B, D, Z}}

# # === # & /@ lis // Boole

or

Boole[# # === #] & /@ lis

Result:

{1, 0, 1, 0, 0}

$\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.