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

| improve this answer | |
$\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).

| improve this answer | |
$\endgroup$

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.