Suppose I have the following two lists:

l1 = {{"apple", "banana", "cream"}, {"beef", "pepper", 
   "salt"}, {"wine", "beer", "beef", "olive"}}
l2 = {"beef:salt:pepper", "apple:cream", "wine:beer:beef:olive"}

For each element in l2 I want to go through l1 and select the element in l2 if it exists in l1, such that the output would be:

{"beef:salt:pepper", "wine:beer:beef:olive"}

I know generally one should use Intersection[l1, l2] yet the format of two lists are different so it turns an empty list. I wonder how one go around this?


1 Answer 1


You can reformat l2, so that you have it in the same format as l1, using StringSplit:

reformatted = StringSplit[#, ":"] & /@ l2

{{"beef", "salt", "pepper"}, {"apple", "cream"}, {"wine", "beer",
"beef", "olive"}}

Intersection[l1, reformatted]

{{"wine", "beer", "beef", "olive"}}

You'll notice that {"beef", "pepper", "salt"} was left out, because order matters. If you don't want to consider the order in which elements appear, you can fix it like this:

Intersection[l1, reformatted, SameTest -> (Sort[#1] === Sort[#2] &)]

{{"beef", "pepper", "salt"}, {"wine", "beer", "beef", "olive"}}

  • $\begingroup$ One could also include the reformatting directly in the SameTest, which would allow to work directly with the original lists $\endgroup$
    – Lukas Lang
    Commented Jul 31, 2019 at 11:14

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.