[英]How should I subtract two vectors or matrices from each other without NumPy?
I have a function that subtracts one matrix of some shape (a nested list) from another matrix of the same shape (assumed to be a nested list of the same size):我有一个 function 从另一个相同形状的矩阵(假设是相同大小的嵌套列表)中减去一个形状的矩阵(嵌套列表):
def subtract(matrix_a, matrix_b):
MATRIX_LENGTH = len(matrix_a)
MATRIX_ROW = len(matrix_a[0])
for i in range(MATRIX_LENGTH):
for j in range(MATRIX_ROW):
matrix_a[i][j] -= matrix_b[i][j]
return matrix_a
The above function iterates through each value of matrix_a and subtracts the value at the same position of matrix_b from matrix_a before returning matrix_a.上面的function遍历matrix_a的每个值,在返回matrix_a之前从matrix_a中减去matrix_b的相同position的值。
This code does not work if I supply a vector (an "un"-nested list).如果我提供向量(“未”嵌套列表),此代码将不起作用。 For example, supplying [1, 2, 3, 4] and [2, 3, 4, 5] to matrix_a and matrix_b respectively will yield TypeError: object of type 'int' has no len()
.例如,分别向 matrix_a 和 matrix_b 提供 [1, 2, 3, 4] 和 [2, 3, 4, 5] 将产生TypeError: object of type 'int' has no len()
。
How should I modify the function to accept "un"-nested lists?我应该如何修改 function 以接受“未”嵌套列表? For educational purposes, I do not want to use NumPy.出于教育目的,我不想使用 NumPy。
Thanks in advance.提前致谢。
Thanks to @LarrytheLlama, I thought of using a try/except/else statement to catch the TypeError.感谢@LarrytheLlama,我想到了使用 try/except/else 语句来捕获 TypeError。 The following code subtracts two vectors or matrices from each other without NumPy:以下代码在没有 NumPy 的情况下将两个向量或矩阵相减:
def subtract(matrix_a, matrix_b):
MATRIX_LENGTH = len(matrix_a)
try:
MATRIX_ROW = len(matrix_a[0])
except TypeError:
for i in range(MATRIX_LENGTH):
matrix_a[i] -= matrix_b[i]
else:
for i in range(MATRIX_LENGTH):
for j in range(MATRIX_ROW):
matrix_a[i][j] -= matrix_b[i][j]
return matrix_a
You can use zip to pair up the values/rows in a list comprehension, and call the function recursively for nested dimensions:您可以使用 zip 在列表理解中配对值/行,并为嵌套维度递归调用 function:
def subtract(A,B):
if isinstance(A,list):
return [ subtract(ra,rb) for ra,rb in zip(A,B) ]
else:
return A-B
This will work for any number of dimensions这适用于任意数量的维度
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.