4
$\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$ Jan 4, 2022 at 19:10

2 Answers 2

4
$\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
    Jan 4, 2022 at 19:11
  • 1
    $\begingroup$ @flinty The output is the same with op ask $\endgroup$
    – yode
    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
    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
    Jan 4, 2022 at 19:17
  • $\begingroup$ Sorry, I have made some mistakes typing. It has been corrected. $\endgroup$
    – Teng
    Jan 4, 2022 at 19:27
2
$\begingroup$
Cases[{___, Alternatives @@ list1 , ___}] @ reflist
{{1, 3}, {4, 6}, {7, 2, 5}}
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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