我正在尝试创建一个不带任何库的矩阵乘法标量函数。 它必须包括列表理解:
A = [[1,2],[3,4]] # 2by2 matrix
scalar = 2 #positive int
product = []
for row in A:
temp = []
for element in row:
temp.append(scalar * element)
product.append(temp)
print(product)
最佳答案
这是一个可能的解决方案:
A = [[1,2],[3,4]] # 2by2 matrix
scalar = 2 #positive int
product = [[i*scalar for i in sublist] for sublist in A]
print(product)
关于Python - 将 for 循环变成单行代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64893927/