How to pick out sublists based upon two numbers in two different positions being equal?

This is a scaled down code of what I'm working with:

assoc1 = <|"T1" -> 1, "T2" -> 2, "T3" -> 3, "Z1" -> 4|>

lis1 = {{{"T1","T2","T1"}, {"Z1","T3","T2"}, {"T1","T1","Z1"}, {"T2","T3","T3"}}}
lis2 = lis1 /. assoc1


What I'm trying to do is to filter through lis1 and make a few different lists which fit the criteria in which numbers in designated spots within sublists of lis2 have the same value . For example let's say I wanted to create another list which is made up of pulled sublists from lis1 in which the numbers in position 1 and position 3 of any sublist given by lis2 had the same value, this would give us a new list of:

newlis1 = {{{"T1","T2","T1"}}}


Likewise, let's say I wanted to only pull out sublists in which the first two or last two numbers within a sublist were equal, this would give two new lists respectively:

newlis2= {{{"T1","T1","Z1"}}} and newlis3 = {{{"T2","T3","T3"}}}

Is there a generic way to do this? I was thinking maybe using DeleteCases but I hadn't gotten anything along those lines to work.

• newlis1 = List /@ Cases[lis1, {a_, _, a_}, All] and {newlis2, newlise3} = List /@ Cases[lis1, {a_, a_, _} | {_, a_, a_}, All]?
– kglr
Commented Aug 25, 2020 at 19:59

First and third:

Cases[lis1, {x_, _, x_}, {2}]


{{"T1", "T2", "T1"}}

First two and last two:

Cases[lis1, {x_, x_, _}, {2}]


{{"T1", "T1", "Z1"}}

Cases[lis1, {_, x_, x_}, {2}]


{{"T2", "T3", "T3"}}

I used Cases out of habit, but your idea with DeleteCases has the advantage that it doesn't change the structure (the level of nesting).

DeleteCases[lis1, Except[{_, x_, x_}], {2}]


{{{"T2", "T3", "T3"}}}

Your example list lis1 has 3 levels, but only one element at the first level. If this is always the case, you could use

Select[lis1 // First,
assoc1[#[[1]]] == assoc1[#[[2]]] ||
assoc1[#[[2]]] == assoc1[#[[3]]] &]


However, if lis1 could have more than 1 "row", you could use something like

Select[#,
assoc1[#[[1]]] == assoc1[#[[2]]] ||
assoc1[#[[2]]] == assoc1[#[[3]]] &] & /@ lis1

newlis1 = List /@ Cases[lis1, {a_, _, b_} /;assoc1[a] == assoc1[b], All]

 {{{"T1", "T2", "T1"}}}

{newlis2, newlis3} = List /@ Cases[lis1, {a_, b_, _} | {_, a_, b_} /;
assoc1[a] == assoc1[b], All]

 {{{"T1", "T1", "Z1"}}, {{"T2", "T3", "T3"}}}

pIck = Pick[#, Apply[Equal, (# /. #2)[[All, #3]], {-2}]] &;

pIck[First@lis1, assoc1, {1, 3}]

 {{"T1", "T2", "T1"}}

pIck[First@lis1, assoc1, ;; 2]

 {{"T1", "T1", "Z1"}}

pIck[First@lis1, assoc1, 2 ;;]

 {{"T2", "T3", "T3"}}