# Re-group sublist element by a reference list

I have a list filled with a large number of elements, eg. {1,2,3,4,5,6,7}

I wanna partition the list by a reference list. The reference list shows how those elements need to be grouped. eg. {{1,3},{4,6},{7,2,5},{9,10,11}...}. The reference list also contains the unwanted element/sublist.

My current methods are:

list1 = {1, 2, 3, 4, 5, 6, 7};
reflist = {{1, 3}, {4, 6}, {7, 2, 5}, {9, 10, 11}};

Flatten[DeleteDuplicates[
Table[Select[reflist, MemberQ[#, list1[[i]]] &], {i, 1,
Length@list1}]], 1]



This methods works but is not efficient. my list1 could be more than half-million unique elements. I am seeking a more effective way to do it.

• Is this more efficient? Select[reflist, Length@Intersection[list1, #] > 0 &]. Commented Jan 4, 2022 at 19:10

Select[reflist, ContainsAll[list1, #] &]


{{1, 3}, {4, 6}, {7, 2, 5}}

• The 8 shouldn't be there, it's not in list1. Commented Jan 4, 2022 at 19:11
• @flinty The output is the same with op ask
– yode
Commented Jan 4, 2022 at 19:13
• yeah that confused me: it says "partition the list by a reference list" so why would the list1 which does not contain an 8 get partitioned into a list-of-lists which does? Commented Jan 4, 2022 at 19:15
• @flinty By the name, he should be a Chinese. Not very good at expressing in English. But my results are the same as his.
– yode
Commented Jan 4, 2022 at 19:17
• Sorry, I have made some mistakes typing. It has been corrected.
– Teng
Commented Jan 4, 2022 at 19:27
Cases[{___, Alternatives @@ list1 , ___}] @ reflist

{{1, 3}, {4, 6}, {7, 2, 5}}

list = {{1, 3}, {4, 6}, {7, 2, 5}, {9, 10, 11}};

e = {1, 2, 3, 4, 5, 6, 7};


Using Cases and SubsetQ

Cases[list, x_ /; SubsetQ[e, x]]


{{1, 3}, {4, 6}, {7, 2, 5}}

Using Pick and ContainsAll

Pick[list, ContainsAll[e, #] & /@ list]


{{1, 3}, {4, 6}, {7, 2, 5}}

list1 = {1, 2, 3, 4, 5, 6, 7};
reflist = {{1, 3}, {4, 6}, {7, 2, 5}, {9, 10, 11}};


Using DeleteCases:

DeleteCases[reflist, x_ /; FreeQ[UniqueElements[{list1, x}], {}]]

(*{{1, 3}, {4, 6}, {7, 2, 5}}*)