简体   繁体   English

用Python中的相同列表减去列表中的列表

[英]Subtract list within list with a same list in Python

I have a list as below: 我有如下列表:

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

Now I would like to subtract all the lists in A with B 现在我想用B减去A中的所有列表

B=[1,1,1]

to get the following result C: 得到以下结果C:

C=[[0,1,2],[3,4,5],[6,7,8]]

I know I can use zip to do two list subtraction, but I cannot use it directly on list within list. 我知道我可以使用zip进行两个列表减法,但是不能直接在列表中的列表上使用它。 How can I do the above subtraction? 我该如何减去? Thanks 谢谢

Using a list comprehension with zip : zip使用列表zip

C = [[a-b for a, b in zip(sublist, B)] for sublist in A]

Alternatively, using a list comprehension with enumerate : 或者,使用带有enumerate的列表理解:

C = [[j-B[i] for i, j in enumerate(sublist)] for sublist in A]

Using 3rd party library NumPy, you can utilize broadcasting to output an array: 使用第三方库NumPy,您可以利用广播来输出数组:

import numpy as np

A = np.array([[1,2,3],[4,5,6],[7,8,9]])
B = np.array([1,1,1])

C = A - B

print(C)

array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])

Using numpy . 使用numpy

Demo: 演示:

import numpy as np
A=[[1,2,3],[4,5,6],[7,8,9]]
B=[1,1,1]
C = [list(np.array(i) - np.array(B)) for i in A]
print(C)

Using operator.sub 使用operator.sub

from operator import sub
A=[[1,2,3],[4,5,6],[7,8,9]]
B=[1,1,1]
C = [list(map(sub, i, B)) for i in A]
print(C)

Output: 输出:

[[0, 1, 2], [3, 4, 5], [6, 7, 8]]
import operator
A=[[1,2,3],[4,5,6],[7,8,9]]B=[1,1,1]
B=[1,1,1]
C=[list(map(operator.sub, i,B)) for i in A]
print C

Here is an alternative approach without the use of NUMPY - 这是一种不使用NUMPY的替代方法-

for innerList in A:
    newInner = []
    for j in range(0, len(innerList)):
        newInner.append(innerList[j] - B[j])
    C.append(newInner)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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