7
$\begingroup$

I have a nested list of the form

{{{{a, 0},{b, 1},{c, 2}}, {{d, 4},{e, 5},{f, 6}}} ... }

where the $...$ just means it goes on like that. On the innermost level, as you can see, I have pairs of the form {string, number}. All I want to do is to delete from this nested list the pairs whose number entry is 0.

For instance, in the above example, I want to delete only the pair {a, 0}.

I've spent the last two hours reading up on answers on this website and elsewhere on the internet, without managing to successfully apply them to this case. Most commands just return the empty list. I also find it very hard to understand the syntax of pretty much all of the list-related commands.

I should also say that I don't really care about the nested structure being preserved or about speed, since the list isn't too big.

Thank you for your time.

$\endgroup$
  • 1
    $\begingroup$ list/.{_, 0} :> Sequence[] $\endgroup$ – Algohi Feb 23 '16 at 1:08
  • $\begingroup$ @Algohi it works, thank you! $\endgroup$ – Guest Feb 23 '16 at 1:10
  • 1
    $\begingroup$ DeleteCases[list, {_, 0}, ∞] also works. $\endgroup$ – bbgodfrey Feb 23 '16 at 1:23
  • 1
    $\begingroup$ @bbgodfrey This DeleteCases command is the first that actually makes sense to me, so thank you very much. $\endgroup$ – Guest Feb 23 '16 at 3:39
  • $\begingroup$ Also Select[#[[-1]] != 0 &][Partition[Flatten[list], 2]] - without nested structure and not fast :)) $\endgroup$ – garej Feb 23 '16 at 10:59
4
$\begingroup$

For the record, so that this question have answers in an Answer block, correct answers given in the comments to the OP include

  • list/.{_, 0} :> Sequence[]
  • DeleteCases[list, {_, 0}, ∞]

In addition, here are two that are similar to the ones above but slightly more specific to the requirements stated in the OP:

  • list/.{_, 0} -> Sequence[] (Rule instead of RuleDelayed)
  • DeleteCases[list, {_, 0}, {3}] (deletes only sublists at level 3)
$\endgroup$
2
$\begingroup$

Let's use a more complex expression than given above to stress the solution methods a bit more.

data = 
  {{{{a, 0}, {b, 1}, {c, 2}}, {{d, 4}, {e, 5}, {f, 6}}},
  {{{{{a, 0}}}, {b, 1}, {c, 2}}, {{d, 4}, {{e, 0}, {f, 6}}}}};

I think the following have advantages over the solutions already given.

data /. {_, 0} -> Nothing
DeleteCases[data, {_, 0}, {-2}]

Both give

{{{{b, 1}, {c, 2}}, {{d, 4}, {e, 5}, {f, 6}}}, 
 {{{{}}, {b, 1}, {c, 2}}, {{d, 4}, {{f, 6}}}}}

The first method I think more easily understood than /. {_, 0} :> Sequence[] and second simply is more robust -- DeleteCases[data, {_, 0}, {3}] fails on this more complex data list.

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