is there an easy way to pull sublists out of a "master list" based upon certain conditions?

Let's say I have a list:




The two lists show two representations of the same thing, i.e. "list2" the elements of 1a = 15, 1b = 15, 1c = 2, 1y= 10. What I'm trying to do is two-fold, first I want to make a list of subsets (derived from list1) which contain 1a in them (the 1a can be in any position). So that would give us the list:


Then I want to take that nlist1 and compare it to list2 to create a new list. The new list is a sublist of nlist1 in which both values given by list2 are equal. That would give the output of:


I tried to tackle this with an If statement but I was having trouble getting the sublists to print the same way they're shown in the list themselves.

  • 1
    $\begingroup$ symbol names cannot start with numbers:list1={{{1a,1b},{1a,1c},{1a,1a},{1y,1y}}} does not work as you intend. You can use list1 = {{{a1, b1}, {a1, c1}, {a1, a1}, {y1, y1}}}; instead. $\endgroup$
    – kglr
    May 27, 2020 at 23:33

3 Answers 3

list1 = {{{a1, b1}, {a1, c1}, {a1, a1}, {y1, y1}}};
list2 = {{{15, 15}, {15, 2}, {15, 15}, {10, 10}}};

assoc = AssociationThread[Flatten @ list1, Flatten @ list2]
 <|a1 -> 15, b1 -> 15, c1 -> 2, y1 -> 10|>
nlist1 = Cases[list1, {a1, _} | {_, a1}, All]
{{a1, b1}, {a1, c1}, {a1, a1}}
Select[Equal @@ # /. assoc &]@nlist1
 {{a1, b1}, {a1, a1}}


Pick[nlist1, Equal @@@ ( nlist1 /. assoc)]
Cases[{a_, b_} /; (Equal[a, b] /. assoc)] @ nlist1
DeleteCases[_?(DuplicateFreeQ[# /. assoc] &)] @ nlist1

all give

 {{a1, b1}, {a1, a1}}
nlist2={Select[Extract[list1,Position[list2, {x_,x_}]], MemberQ[#,a1]&]}

{{{a1, b1}, {a1, a1}}}


a = {{{a1, b1}, {a1, c1}, {a1, a1}, {y1, y1}}};

b = {{{15, 15}, {15, 2}, {15, 15}, {10, 10}}};

Cases[{x_, {y_, y_}} /; MemberQ[x, a1] :> x] @ Transpose[First /@ {a, b}]

{{a1, b1}, {a1, a1}}


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.