# How to delete element from nested list with a criterion

I have a nested list, whose sublists have different numbers of levels. This makes my problem different from the other problems on the site.

pts={{{{a1, b1, c11}}, {{a2, b1, c21}}, ..., {{an, b1, cn11}, {an, b1, cn12}, {an, b1, cn13}, {an, b1, cn14}}, ..., {{a(m-1), b1, c(m-1)1}}, {{am, b1, cm1}}}, ..., {{{a1, bn, c1n}}, ... ,{{am, bn, cmn}}}}


I need to delete the element if the difference between its 3rd number c and a reference value cref is larger than a threshold. I hope to obtain a list like

Newpts={{{{a1, b1, c11}}, {{a2, b1, c21}}, ..., {{an, b1, cn11}}, ..., {{a(m-1), b1, c(m-1)1}}, {{am, b1, cm1}}}, ..., {{{a1, bn, c1n}}, ... ,{{am, bn, cmn}}}}


in which {an, b1, cn12}, {an, b1, cn13}, {an, b1, cn14} have been deleted according to Abs[c-cref]>10^-5 say.

Here is an example

pts={{{{0, 1, 1.129}}, {{0.005, 1, 1.129 }}, {{0.01, 1, 0.56471}, {0.01,
1, 0.56471}, {0.01, 1, 0.56472}, {0.01, 1, 1.129 }}, {{0.015, 1,
0.56471}, {0.015, 1, 0.56471 }, {0.015, 1, 0.56472}, {0.015, 1,
1.129}}, {{0.02, 1, 1.129}}, {{0.025, 1, 0.56471}, {0.025, 1,
0.56472}, {0.025, 1, 0.56472}, {0.025, 1, 1.1285}}, {{0.03, 1,
0.58219}}}, {{{0, 2, 1.129}}, {{0.005, 2, 1.129 }}}}


I want to delete the element whose 3rd element is close to a reference value, say cref=0.5647189, the expected result is

Newpts={{{{0, 1, 1.129}}, {{0.005, 1, 1.129 }}, {{0.01, 1, 1.129 }}, {{0.015, 1, 1.129}}, {{0.02, 1, 1.129}}, {{0.025, 1, 1.1285}}, {{0.03, 1, 0.58219}}}, {{{0, 2, 1.129}}, {{0.005, 2, 1.129 }}}}


I guess it should use DeleteCases. Thank you in advance!

• Does pts /. {_?NumericQ, _?NumericQ, c_?NumericQ /; c-ct < 10^-5} :> Nothing work? You could also try the levelspec {-2} in DeleteCases if the triples are all at the lowest level. An explicit example, edited into your post, with the desired output will helpful for testing. Jan 7, 2022 at 5:03
• @march I have added an example for testing.
– lxy
Jan 7, 2022 at 12:05

I think the best way to do this is to use the level specification for DeleteCases, which will work provided that the ordered triples of numbers are always at the lowest level possible in their list. Using the explicit example from the OP,

DeleteCases[pts, {_?NumericQ, _?NumericQ, c_?NumericQ} /; Abs[c - cref] < 10^(-5), {-2}]


yields a list identical to Newpts in the example. The point is that we want to look at the second-to last level of the list, where the ordered triples will be located. (The {-1} level is the level of the numbers in each of these lists.)

This also works:

pts /. {_?NumericQ, _?NumericQ, c_?NumericQ /; Abs[c - cref] < 10^(-5)} :> Nothing


A minor variation of the second answer by @march: Using the Between function,

cref = 0.5647189;
\[Epsilon] = 10^(-5);

result = pts /. {_?NumericQ, _?NumericQ,
x_?NumericQ /;
Between[x, {cref - \[Epsilon], cref + \[Epsilon]}]} ->  Nothing

result == Newpts (*True*)