Eniola
Eniola

Reputation: 133

Subtracting a list from a list of lists

I am trying to delete list from a list of lists. For instance:

n = [[1,2,3], [2,3,4], [43,2,5]]
m = [4,5,6]

I want to subtract m[0], from all the values in n[0], then go to m[1], and subtract m[1] from all the values in n[1], etc....

Finally, I want to have something like this as my output

Output = [[3,2,1], [3,2,1], [37,4,1]]

Here is my code:

def diff(n,m):
    for i in range(0,3):
        newlist = [[abs(m[i]-value) for value in sublist]
                   for sublist in n]
    return newlist
n = [[1,2,3], [2,3,4], [43,2,5]]
m = [4,5,6]

diff(n,m)

Output = [[3,2,1], [3,2,1], [37,4,1]]

Upvotes: 2

Views: 528

Answers (2)

Kelly Bundy
Kelly Bundy

Reputation: 27599

Just a pythonic list comprehension (with zip instead of indexes)...

[[abs(b-x) for x in a] for a, b in zip(n, m)]

Upvotes: 3

Nick
Nick

Reputation: 147166

You need to only subtract m[i] from the values in n[i], but your code is subtracting m[i] from all elements of n, but then only returning the result from subtracting m[2] since you overwrite newlist in each pass through the for loop. Here's a list comprehension that does what you want:

n = [[1,2,3], [2,3,4], [43,2,5]]
m = [4,5,6]

o = [[abs(v-m[i]) for v in n[i]] for i in range(len(m))]
print(o)

Output:

[[3, 2, 1], [3, 2, 1], [37, 4, 1]]

Upvotes: 1

Related Questions