Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to match a nested list with list

The problem is I'm trying to compare nested list and list without the same value or element ?

lst3 = [1, 6, 7, 10, 13, 28]
lst4 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]] 

lst5 = [list(filter(lambda x: x not in lst3, sublist)) for sublist in lst4]

which returns:

[[17, 18, 21, 32], [11, 14], [5, 8, 15, 16]]

but I would like to get the number that don't match from l3. Here an example:

[[1,6,7,10,28],[1,6,10],[1,7,13,28]]

I would like the results to be: [[1,6,7,10,28],[1,6,10],[1,7,13,28]]

like image 308
Sofreshnclean Avatar asked Feb 03 '26 09:02

Sofreshnclean


2 Answers

In your example you are comparing each element in each sublist with lst3.

lst5 = [list(filter(lambda x: x not in lst3, sublist)) for sublist in lst4]

Problem is that you are asking whether each x from sublist is not in lst3 which is going to give you the remaining results from the sublist. You may want to do it the other way around.

lst5 = [list(filter(lambda x: x not in sublist, lst3)) for sublist in lst4]

Not only does it give you the answers you want but I even noticed you made a mistake in your expected results:

[[1, 6, 7, 10, 28], [1, 6, 10], [7, 10, 13, 28]]

Compared to yours:

[[1, 6, 7, 10, 28], [1, 6, 10], [1, 7, 13, 28]]

(See the last nested array)

Online example: https://onlinegdb.com/Hy8K8GPSB

like image 200
Dandré Avatar answered Feb 05 '26 01:02

Dandré


Rather than using things like filter and lambda, you could more readably just use a list comprehension:

lst5 = [[x for x in lst3 if not x in sublist] for sublist in lst4]

Which is

[[1, 6, 7, 10, 28], [1, 6, 10], [7, 10, 13, 28]]

This differs slightly from what you gave as your expected output, but I think that you made a typographical error in the third sublist of that expected output.

like image 39
John Coleman Avatar answered Feb 05 '26 02:02

John Coleman



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!