Python - 将 for 循环变成单行代码

标签 python matrix matrix-multiplication scalar

我正在尝试创建一个不带任何库的矩阵乘法标量函数。 它必须包括列表理解:

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/

相关文章:

python - 卷积层中的偏差真的会对测试精度产生影响吗?

matlab - SVM 中的 Gram 矩阵/核不是半正定的

python - Gurobi错误: Q matrix is not positive semi-definite (PSD)

numpy - 为什么特征向量与对应特征值的乘积不等于原矩阵与特征向量的乘积?

c++ - Eigen C++ 断言失败

python - 非常大的矩阵向量积

python - 如何将外部标签添加到 BeautifulSoup 对象

python - 重新创建 Web Audio API GainNode 行为

Python:断言字符串是否与格式匹配

performance - 下秩矩阵的计算