3

I have the following lists

list1 = [[x1,1,b1],[x2,1,b1],[x3,1,b1],[x4,1,b1]]

and the following

list2 = [[x1,0,b1],[x5,0,b1],[x2,0,b1],[x7,0,b1]]

I don't know how to create a final list like the

list3 = [[x1,1,b1],[x2,1,b1],[x3,1,b1],[x4,1,b1],[x5,0,b1],[x7,0,b1]]

To keep the first list1 and add to list1 elements from list2 only if the list2[0][0] element does not exist in list1

I tried something like the following with several combinations

for i in list1:
    for i2 in list2:
        if i[0][0] != i2[0][0]
            list3.append(i2)

But list3 displays elements which are common

SuperKogito
  • 2,998
  • 3
  • 16
  • 37
Evridiki
  • 323
  • 3
  • 16

4 Answers4

5

The logic of your attempt is wrong. Your double loop fails because when looping on all elements of both combined lists, the difference test has to be true at some point.

Let me propose a faster & working alternative:

  • Extract the first elements of each list1 sublists in a set for quick match.
  • Then create new list by adding list1 and the filtered elements of list2

Like this:

list1 = [['x1',1,'b1'],['x2',1,'b1'],['x3',1,'b1'],['x4',1,'b1']]
list2 = [['x1',0,'b1'],['x5',0,'b1'],['x2',0,'b1'],['x7',0,'b1']]

list_items = {l[0] for l in list1}

list3 = list1 + [l for l in list2 if l[0] not in list_items]

result:

>>> list3
[['x1', 1, 'b1'],
 ['x2', 1, 'b1'],
 ['x3', 1, 'b1'],
 ['x4', 1, 'b1'],
 ['x5', 0, 'b1'],
 ['x7', 0, 'b1']]
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
0

You have to use sets and make a union to eliminate duplicates:

list1 = [[1,1,1], [1,1,2]]
list2 = [[1,1,3], [1,1,2]]

list1 = set([tuple(x) for x in list1])
list2 = set([tuple(x) for x in list2])

res = list1.union(list2)

this will yield {(1, 1, 3), (1, 1, 1), (1, 1, 2)}

and to have it as a list of lists you can do: [list(x) for x in res]

andreihondrari
  • 5,743
  • 5
  • 30
  • 59
0

You can use a dictionary to merge two lists:

from itertools import chain

x1, x2, x3, x4, x5, x7 = 'x1', 'x2', 'x3', 'x4', 'x5', 'x7'
b1, b2, b3 = 'b1', 'b2', 'b3'

list1 = [[x1, 1, b1], [x2, 1, b1], [x3, 1, b1], [x4, 1, b1]]
list2 = [[x1, 0, b1], [x5, 0, b1], [x2, 0, b1], [x7, 0, b1]]

d = {i[0]: i for i in chain(list2, list1)}
sorted(d.values(), key=lambda x: x[0])
# [['x1', 1, 'b1'], ['x2', 1, 'b1'], ['x3', 1, 'b1'], ['x4', 1, 'b1'], ['x5', 0, 'b1'], ['x7', 0, 'b1']]
Mykola Zotko
  • 15,583
  • 3
  • 71
  • 73
-3

Append the lists together, so

list3.append(list2)
list3.append(list1)
Ru Chern Chong
  • 3,692
  • 13
  • 33
  • 43