1
$\begingroup$

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

Let's say I have a list:

list1={{{1a,1b},{1a,1c},{1a,1a},{1y,1y}}}

and:

list2={{{15,15},{15,2},{15,15},{10,10}}

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:

nlist1={{{1a,1b},{1a,1c},{1a,1a}}}

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:

nlist2={{{1a,1b},{1a,1a}}}

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.

$\endgroup$
1
  • 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 '20 at 23:33
2
$\begingroup$
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}}

Also

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

all give

 {{a1, b1}, {a1, a1}}
$\endgroup$
0
$\begingroup$
nlist2={Select[Extract[list1,Position[list2, {x_,x_}]], MemberQ[#,a1]&]}

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

Lists

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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