6
$\begingroup$

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.

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

4 Answers 4

5
$\begingroup$
Select[reflist, ContainsAll[list1, #] &]

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

$\endgroup$
8
  • $\begingroup$ The 8 shouldn't be there, it's not in list1. $\endgroup$
    – flinty
    Commented Jan 4, 2022 at 19:11
  • 1
    $\begingroup$ @flinty The output is the same with op ask $\endgroup$
    – yode
    Commented Jan 4, 2022 at 19:13
  • $\begingroup$ 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? $\endgroup$
    – flinty
    Commented Jan 4, 2022 at 19:15
  • $\begingroup$ @flinty By the name, he should be a Chinese. Not very good at expressing in English. But my results are the same as his. $\endgroup$
    – yode
    Commented Jan 4, 2022 at 19:17
  • $\begingroup$ Sorry, I have made some mistakes typing. It has been corrected. $\endgroup$
    – Teng
    Commented Jan 4, 2022 at 19:27
2
$\begingroup$
Cases[{___, Alternatives @@ list1 , ___}] @ reflist
{{1, 3}, {4, 6}, {7, 2, 5}}
$\endgroup$
1
$\begingroup$
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}}

$\endgroup$
1
$\begingroup$
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}}*)
$\endgroup$

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.