Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add item to list if not already exists

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?

like image 522
moatze Avatar asked Dec 08 '25 18:12

moatze


1 Answers

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!

like image 129
Damián Montenegro Avatar answered Dec 11 '25 07:12

Damián Montenegro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!