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

时间:2016-10-20 18:38:45

标签: python list

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.

4 个答案:

答案 0 :(得分:2)

seen = set()
res = []
for a, b in zip(l1, l2):
    subres = []
    for item in a:
        seen.add(item)
        if item not in b and item not in seen:
            subres.append(item)
    for item in b:
        seen.add(item)
        if item not in a and item not in seen:
            subres.append(item)
    res.append(subres)

答案 1 :(得分:2)

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]]

答案 2 :(得分:1)

For what it seems like you are looking for, I would keep a set of previous values.

old_values =  {}
ll3 = []
for list_a, list_b in zip(ll1,ll2):
  temp_list = []
  for item in list_a:
    if item in old_values or item in list_b:
      pass
    else:
      temp_list.append(item)
      old_values.add(item)
  for item in list_b:
    if item in old_values or item in list_a:
      pass
    else:
      temp_list.append(item)
      old_values.add(item)
  ll3.append(temp_list)

答案 3 :(得分:-1)

In general - assuming that order of elements in resulting sub-lists is not important and 2 lists are of the same length, you may use zip and set

ll3 = [set(l1 + l2) - set(l1).intersection(l2) for l1, l2 in zip(ll1, ll2)]
seen = set()
for idx, elem in enumerate(ll3):
    ll3[idx] = list(elem - seen)
    seen.update(elem)