Reputation: 148
I'm new to Python and got following problem:
a = [[0,abc,1],[0,def,1]]
b = [abc,jkl]
Output should be:
c = [[0,abc,1],[0,def,1],[0,jkl,1]]
Can anyone help me out there?
Upvotes: 2
Views: 20222
Reputation: 12587
How about this?
>>> a = [[0,'abc',1],[0,'def',1]]
>>> b = ['abc','jkl']
>>> c = a[:]
>>> for i in b:
... if [0,i,1] not in a:
... c.append([0,i,1])
...
>>> c
[[0, 'abc', 1], [0, 'def', 1], [0, 'jkl', 1]]
Upvotes: 3
Reputation: 839
It can be done with the following code:
In [3]: a = [[0,'abc',1],[0,'def',1]]
In [4]: b = ['abc','jkl']
In [5]: c = a[:]
In [6]: c.extend([[0,e,1] for e in b if e not in [x for _,x,_ in a]])
In [7]: c
Out[8]: [[0, 'abc', 1], [0, 'def', 1], [0, 'jkl', 1]]
Hope this helps!
Upvotes: 6
Reputation: 5629
Use not in to check if it contains or not
a = [[0,abc,1],[0,def,1]]
b = [abc,jkl]
c = []
for i in a:
if i not in c:
c.append(i)
for j in b:
if j not in c:
c.append(j)
Upvotes: 1