Common elements in list of lists

Viewed 187

I have 2 list-of-lists

a = [(468, 15), (336, 280), (200, 90), (180, 150), (180, 150), (180, 150)]
b = [(200, 200), (200, 90), (200, 90), (180, 150), (180, 150)]

I want to find elements that are the same between both lists and eliminate them. b[0] is NOT present in a, only one of b[1] & b[2] is present in a, b[3] and b[4] are BOTH present in a.

I need the maximum occurrence in each list to be sent to another list (the others are counted as repeats) i.e. I need this to be my output

combined = [(468, 15), (336, 280), (200, 200), (200, 90), (200, 90), (180, 150), (180, 150), (180, 150)]

Note: I have gone through solutions but they convert these lists into "sets" which eliminates the 'repeat' occurrences.

Is there a simple way to do this?

Edit: Explanation of how the output was made

(468, 15) occurs 1 time in a. (336, 280) occurs 1 time in a. (200, 200) occurs 1 time in b. (200, 90) occurs 1 time in a, 2 times in b. (180, 150) occurs 3 times in a, 2 times in b.

The output is the max occurrence between both lists i.e.

(468, 15) once. (336, 280) once. (200, 200) once. (200, 90) twice. (180, 150) thrice.

Making the list as given in combined

4 Answers

Since order does not matter, you can put all items into a set, and add the max occurrences of each item:

a = [(468, 15), (336, 280), (200, 90), (180, 150), (180, 150), (180, 150)]
b = [(200, 200), (200, 90), (200, 90), (180, 150), (180, 150)]

res = [each for each in set(a + b) for i in range(max(a.count(each), b.count(each)))]

res would look like this:

[(180, 150), (180, 150), (180, 150), (200, 200), (468, 15), (336, 280), (200, 90), (200, 90)]

One option would be using collections.Counter. At least to my eyes this corresponds the best to how I think about the problem:

from collections import Counter

ca = Counter(a)
cb = Counter(b)

result = [
    element  # every element
    for element in ca | cb  # that is in either input
    for _ in range(max(ca[element], cb[element]))  # the larger amount of times it occurs
]

This will of course only work when your elements are hashable (= can be keys in a dictionary, or elements in a set).

try this:

a = [(468, 15), (336, 280), (200, 90), (180, 150), (180, 150), (180, 150)]
b = [(200, 200), (200, 90), (200, 90), (180, 150), (180, 150)]


[[d] * max(a.count(d), b.count(d)) for d in set(a+b)]

The above can be resolved by adding the lists and removing the duplicates.

example as below:

a = [(468, 15), (336, 280), (200, 90), (180, 150), (180, 150), (180, 150)]
b = [(200, 200), (200, 90), (200, 90), (180, 150), (180, 150)]
mylist = list(dict.fromkeys(a+b))
print(mylist)
Related