# Intersection of two lists with different formats

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?

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"}}

• One could also include the reformatting directly in the SameTest, which would allow to work directly with the original lists – Lukas Lang Jul 31 '19 at 11:14