3
$\begingroup$

This question already has an answer here:

I have the following list of lists.

 data = {{0, 0, 0}, {1, 0, 0}, {2, 0, 1}, {3, 0, 0}, {4, 0, 0}, {5, 0, 3}}

I want to drop all the lists with 0 as the 3rd entry i.e. {m,n,0}. How can I do this?

$\endgroup$

marked as duplicate by Jason B., Henrik Schumacher, Kuba list-manipulation Dec 3 '18 at 21:46

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

4
$\begingroup$

Easy (but probably not the fastest) way:

DeleteCases[data, {_, _, 0}]

{{2, 0, 1}, {5, 0, 3}}

This might be a bit faster for longer lists as it entirely avoids pattern matching:

Delete[data, Partition[Random`Private`PositionsOf[data[[All, 3]], 0], 1]]

Here a speed test:

data = RandomInteger[{0, 5}, {1000000, 3}];
a = DeleteCases[data, {_, _, 0}]; // AbsoluteTiming // First
b = Delete[data, Partition[Random`Private`PositionsOf[data[[All, 3]], 0], 1]]; // 
   AbsoluteTiming // First
a == b

0.407339

0.027375

True

$\endgroup$
1
$\begingroup$

Another way

data = {{0, 0, 0}, {1, 0, 0}, {2, 0, 1}, {3, 0, 0}, {4, 0, 0}, {5, 0, 3}}
Pick[data, Unitize@data[[;; , 3]], 1]

{{2, 0, 1}, {5, 0, 3}}

And a timing comparison to DeleteCases

SeedRandom[1234]
Block[
 {data = RandomInteger[{0, 5}, {1000000, 3}], times, m1, m2},
 times = {
  AbsoluteTiming[m1 = DeleteCases[data, {__, 0}]][[1]],
  AbsoluteTiming[m2 = Pick[#, Unitize@#[[;; , 3]], 1] &@data][[1]]
 };
 {times, m1 == m2}
]

{{0.403632, 0.031339}, True}

$\endgroup$

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