1

I have 2 lists one :

[(12,23),(12,45),(12,23),(2,5),(1,2),(2,4),(7,34)] which goes up to around 1000 elements and another:

[(12,23),(12,45),(12,23),(2,5),(1,2),(2,66),(34,7)] which goes up to around 241 elements.

What I want is to check to see if the lists contain any of the same elements and then put them in a new list.

so the new list becomes

[(12,23),(12,45),(12,23),(2,5),(1,2)]

John Smith
  • 1,089
  • 3
  • 18
  • 37
  • As long as it the new list contains all the elements that are the same in both, oder doesn't matter – John Smith Apr 23 '13 at 07:35
  • Possible duplicat: http://stackoverflow.com/questions/3847386/testing-if-a-list-contains-another-list-with-python – tostao Apr 23 '13 at 07:36
  • @JohnSmith Also, just say a value occured 3 times in the first list and 2 times in the last list, how many times would it be in the newlist? Or does it not matter – jamylak Apr 23 '13 at 07:55
  • @tostao I think this is asking for an intersection of lists which is different to that question – madth3 Apr 23 '13 at 18:53
  • Check this question: http://stackoverflow.com/q/642763/422353 – madth3 Apr 23 '13 at 18:56

1 Answers1

13

This doesn't include duplicates

>>> A = [(12,23),(12,45),(12,23),(2,5),(1,2),(2,4),(7,34)]
>>> B = [(12,23),(12,45),(12,23),(2,5),(1,2),(2,66),(34,7)]
>>> set(B).intersection(A) # note: making the smaller list to a set is faster
set([(12, 45), (1, 2), (12, 23), (2, 5)])

Or

>>> A = [(12,23),(12,45),(12,23),(2,5),(1,2),(2,4),(7,34)]
>>> B = [(12,23),(12,45),(12,23),(2,5),(1,2),(2,66),(34,7)]
>>> filter(set(B).__contains__, A)
[(12, 23), (12, 45), (12, 23), (2, 5), (1, 2)]

This returns every item in B if it occured in A, which produces the result you give in the example, however the set is probably what you want.

Since I don't know exactly what you are using this for, I'll suggest one more solution which returns a list, containing the items that occur in both lists, the minimum amount of times they occurred in either list (unordered). This differs from the set solution above which only returns each item the number of times it occurred in the other and doesn't care how many times it occurred in the first. This uses Counter for the intersection of multisets.

>>> from collections import Counter
>>> A = [(12,23),(12,45),(12,23),(2,5),(1,2),(2,4),(7,34)]
>>> B = [(12,23),(12,45),(12,23),(2,5),(1,2),(2,66),(34,7)]
>>> list((Counter(A) & Counter(B)).elements())
[(1, 2), (12, 45), (12, 23), (12, 23), (2, 5)]
jamylak
  • 128,818
  • 30
  • 231
  • 230
  • Given that `B` is significantly smaller than `A`, I’d suggest you to exchange each other in the statements. Also, the filter method is way faster than the set intersection. – poke Apr 23 '13 at 07:50
  • @poke good idea I've change them, I'll add a note too – jamylak Apr 23 '13 at 07:53