CF84 CF84 - 1 month ago 9
Python Question

Python: how to merge two lists of lists together, avoiding repetitions?

I have two lists of lists:

ll1=[[17],[35,6],[47,58,86]]


ll2=[[19],[75,8],[17,58,86]]


How could I merge them, perhaps in a
for
loop, creating a new list of lists
ll3
, and skipping repeated values?

The intended outcome would be:
ll3=[[17,19],[35,6,75,8],[47,58,86]]


Which is equal to merging the two lists of lists together and then getting rid or the repeated values.

Answer

The previous answers don't appear to meet your requirement that lists can be of different sizes.

My solution makes use of set intersections and unions. N.B. I am using Python2, change zip_longest to izip_longest.

ll1=[[17],[35,6],[47,58,86]]
ll2=[[19],[75,8],[17,58,86]]

from itertools import zip_longest

ll3 = []
seen = set()
for a, b in zip_longest(ll1, ll2, fillvalue=[]):
    new = (set(a) | set(b)) - seen
    ll3.append(list(new))
    seen |= new
print (ll3)

This will print:

[[17, 19], [8, 75, 35, 6], [58, 86, 47]]

This will also work if:

ll1=[[17],[35,6],[47,58,86],[5]]
ll2=[[19],[75,8],[17,58,86]]

returning:

[[17, 19], [8, 75, 35, 6], [58, 86, 47], [5]]