Mahir
Mahir

Reputation: 400

How to find different values in a nested list and find it's differences in Python 3?

I have two nested lists, like this:

list_1 = [[4,9,2],[3,5,7],[8,1,5]]
list_2 = [[4,9,2],[3,5,7],[8,1,6]]

I want to find the different values in between this two nested lists, and also it's differences. In the above lists, the different values are 5 and 6, so the difference is: -1(5-6). Note that no common values will be listed.

I want to store it in a list and print it's output:

[-1]

Another example:

list_1 = [[3, 6, 7], [4, 9, 9], [7, 6, 9]]
list_2 = [[6, 7, 2], [1, 5, 9], [8, 3, 4]]

The output should be like this:

[-3,-1,5,3,4,-1,3,5]

If all of them are common, it should return an empty list: []

Upvotes: 1

Views: 89

Answers (4)

user3684792
user3684792

Reputation: 2611

from itertools import chain 

[l1-l2 for l1, l2 in zip(chain(*list_1),chain(*list_2)) if l1-l2]

Upvotes: 1

Austin
Austin

Reputation: 26057

Use a simple list-comprehension:

list_1 = [[3, 6, 7], [4, 9, 9], [7, 6, 9]]
list_2 = [[6, 7, 2], [1, 5, 9], [8, 3, 4]]

print([x-y for i in range(len(list_1)) for x, y in zip(list_1[i], list_2[i]) if x-y])
# [-3, -1, 5, 3, 4, -1, 3, 5]

Or use itertools.chain:

from itertools import chain

list_1 = [[3, 6, 7], [4, 9, 9], [7, 6, 9]]
list_2 = [[6, 7, 2], [1, 5, 9], [8, 3, 4]]

print([x-y for x, y in zip(chain(*list_1), chain(*list_2)) if x-y])
# [-3, -1, 5, 3, 4, -1, 3, 5]

Upvotes: 0

Paul Panzer
Paul Panzer

Reputation: 53119

Another itertools approach using chain.from_iterable to flatten the nested lists and map to mass apply subtraction and filter to discard equal pairs.

>>> import itertools

Example 1:

>>> list_1 = [[4,9,2],[3,5,7],[8,1,5]]
>>> list_2 = [[4,9,2],[3,5,7],[8,1,6]]
>>> 
>>> list(filter(None, map(int.__sub__, *map(itertools.chain.from_iterable, (list_1, list_2)))))
[-1]

Example 2:

>>> list_1 = [[3, 6, 7], [4, 9, 9], [7, 6, 9]]
>>> list_2 = [[6, 7, 2], [1, 5, 9], [8, 3, 4]]
>>> 
>>> list(filter(None, map(int.__sub__, *map(itertools.chain.from_iterable, (list_1, list_2)))))
[-3, -1, 5, 3, 4, -1, 3, 5]

Upvotes: 0

Kasravnd
Kasravnd

Reputation: 107357

As a pure functional, but a little obscure, approach you can use itertools.starmap() and itertools.chain() plus zip and operator.sub:

In [165]: list(starmap(sub, chain.from_iterable(starmap(zip, zip(list_1, list_2)))))
Out[165]: [-3, -1, 5, 3, 4, 0, -1, 3, 5]

Another yet more understandable way is to use a flatten function for flatten your nested lists with then use a simple list comprehension and zip:

In [168]: def flatten(lst):
     ...:     return [i for sub in lst for i in sub]
     ...: 

In [169]: [i-j for i, j in zip(flatten(list_1), flatten(list_2))]
Out[169]: [-3, -1, 5, 3, 4, 0, -1, 3, 5]
# or starmap(sub, zip(flatten(list_1), flatten(list_2)))

Upvotes: 0

Related Questions