简体   繁体   中英

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]]

只是一个pythonic列表理解(使用zip而不是索引)......

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

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]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM