10
$\begingroup$

Given

t1 = {{14, {{1, 2, 3}}}, {15, {}}, {16, {{0, 0, 4}}}, {17, {{0, 1, 4}, {2, 2, 3}}}, {18, {{0, 3, 3}, {1, 1, 4}}}, {u, {{1, 0, 2}, {2, 3, 0}, {2, 3, 4}}}}

I want to exclude all elements where the second part is empty and also the sub-elements having at least one zero. So I would get

{{14, {{1, 2, 3}}}, {17, {{2, 2, 3}}}, {18, {{1, 1, 4}}}, {u, {{2, 3, 4}}}}

I tried

Cases[t1, {d_, {{a_, b_, c_}}} /; a != 0 \[And] b != 0 \[And] c != 0]

But that excludes too many cases.

$\endgroup$
0

5 Answers 5

6
$\begingroup$
lst = {{14, {{1, 2, 3}}}, {15, {}}, {16, {{0, 0, 4}}}, {17, {{0, 1, 4}, {2, 
     2, 3}}}, {18, {{0, 3, 3}, {1, 1, 4}}}, {u, {{1, 0, 2}, {2, 3, 
     0}, {2, 3, 4}}}};

all elements where the second part is empty

lst /. {_, {}} :> Nothing

the sub-elements having at least one zero.

lst /. {a___, {___, 0, ___}, b___} :> {a, b};

make them together

r1 = {_, {}} :> Nothing;
r2 = {a___, {___, 0, ___}, b___} :> {a, b};
lst //. r2 /. r1
{{14, {{1, 2, 3}}}, {17, {{2, 2, 3}}}, {18, {{1, 1, 4}}}, {u, {{2, 3, 4}}}}
$\endgroup$
7
$\begingroup$
Fold[DeleteCases[##, All] &][ t1, {{___, 0, ___}, {_, {}}}]
{{14, {{1, 2, 3}}}, {17, {{2, 2, 3}}}, {18, {{1, 1, 4}}}, {u, {{2, 3, 4}}}}

Also

Cases[{a_, b : Except[{} | {{___, 0, ___} ..}]} :> {a, Select[FreeQ[0]] @ b}] @ t1
 {{14, {{1, 2, 3}}}, {17, {{2, 2, 3}}}, {18, {{1, 1, 4}}}, {u, {{2, 3, 4}}}}
$\endgroup$
4
$\begingroup$
DeleteCases[{_, {}}]@
  MapAt[DeleteCases[_List?(MemberQ[0])], t1, {All, 2}]

(* Out:
{{14, {{1, 2, 3}}}, {17, {{2, 2, 3}}},
 {18, {{1, 1, 4}}}, { u, {{2, 3, 4}}}} *)
$\endgroup$
3
$\begingroup$
lst = {{14, {{1, 2, 3}}}, {15, {}}, {16, {{0, 0, 4}}},
      {17, {{0, 1, 4}, {2, 2, 3}}}, {18, {{0, 3, 3}, {1, 1, 4}}},
      {u, {{1, 0, 2}, {2, 3, 0}, {2, 3, 4}}}};

A variant using DeleteCases and Cases:

Cases[DeleteCases[lst, {___, 0, ___}, ∞], Except[{_, {}}]]

(*{{14, {{1, 2, 3}}}, {17, {{2, 2, 3}}}, {18, {{1, 1, 4}}}, {u, {{2, 3, 4}}}}*)
$\endgroup$
2
$\begingroup$
list =
  {{14, {{1, 2, 3}}},
   {15, {}},
   {16, {{0, 0, 4}}},
   {17, {{0, 1, 4}, {2, 2, 3}}},
   {18, {{0, 3, 3}, {1, 1, 4}}},
   {u, {{1, 0, 2}, {2, 3, 0}, {2, 3, 4}}}};

via Position

p = Most /@ Position[list, {} | 0]

{{2}, {3, 2, 1}, {3, 2, 1}, {3, 2, 2}, {3, 2, 2}, {4, 2, 1}, {5, 2, 1}, {6, 2, 1}, {6, 2, 2}}

Cases[{_, {__}}] @ Delete[p] @ list

returns

{{14, {{1, 2, 3}}}, 
 {17, {{2, 2, 3}}}, 
 {18, {{1, 1, 4}}},
 {u, {{2, 3, 4}}}}
$\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.