TransWikia.com

Cases for nested lists

Mathematica Asked on February 11, 2021

I have a nested list where each element looks like

{{x, y}, {{a, b}, {c, d}}}

I would like to extract elements of a list with $ b < 0 $, so I look for structure

{{x1, y1}, {{a1, b1}, {c1, d1}}},
 {x1, y1}, {{a1, b1}, {c1, d1}}},
 ...}

First I try

Cases[list, {A_, B_} /; B < 0, 3]

but this gives undesired results:

{{x1, y1}, {a1, b1}, {x2, y2}, {a2, b3}, ...}

so original structure of list disappears and I have. Then I try

Cases[list, {A_, B_} /; B < 0, {3}]

and obtain a list of pairs

{{a1, b1}, {a2, b2}, ...}

What should I do to obtain the desired results?

The second question is how to deal with list with the following structure:

{ {{x1,y1},{{a1,-1},{a2,b2},{a3,b3}}}, {{x2,y2},{{a4,-1},{a5,b4}}} }

I mean that a number of pairs {ai,bi} in the second ”part” of element can be different for each element.

2 Answers

lst = {{{x1, y1}, {{a1, 1}, {c1, d1}}}, 
   {{x2,  y2}, {{a2, -1}, {c2, d2}}}, 
   {{x3, y3}, {{a3, 1}, {c3, d3}}},
   {{x4, y4}, {{a4, -1}, {c4, d4}}}};

Cases[{_, {{_, _?Negative}, __List}}] @ lst
 {{{x2, y2}, {{a2, -1}, {c2, d2}}}, 
  {{x4, y4}, {{a4, -1}, {c4, d4}}}}
Select[#[[2, 1, 2]] < 0 &] @ lst
{{{x2, y2}, {{a2, -1}, {c2, d2}}},
 {{x4, y4}, {{a4, -1}, {c4, d4}}}}
Pick [lst, Negative[lst[[All, 2, 1, 2]]]]
{{{x2, y2}, {{a2, -1}, {c2, d2}}}, 
 {{x4, y4}, {{a4, -1}, {c4, d4}}}}

Answered by kglr on February 11, 2021

Not to take away from kglr’s wonderful answer, but using their defined example lst, we can arrange a slightly more general application of Cases:

Cases[a_:>a/;a[[2,1,2]]<0][lst]

Same output as kglr.

In this way, it is somewhat an amalgam of the methods shown by kglr. You’ll need to know the position of your value in advance, of course, and you can then designate the desired conditions.

What if you don’t know the position of the values that you want to satisfy the condition?

Try this:

Extract[List@*First/@Position[a_/;a<0][Last/@lst]][lst]

Same output.

Answered by CA Trevillian on February 11, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP