【问题标题】:Python - Turning a for-loop into a one-linerPython - 将 for 循环变成单线
【发布时间】:2020-11-18 13:21:09
【问题描述】:

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

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)

【问题讨论】:

    标签: python matrix matrix-multiplication scalar


    【解决方案1】:

    这是一个可能的解决方案:

    A = [[1,2],[3,4]] # 2by2 matrix
    
    scalar = 2 #positive int
    
    product = [[i*scalar for i in sublist] for sublist in A]
    
    print(product)
    

    【讨论】:

      【解决方案2】:

      或者,您可以使用 lambdas 和 map 获得一些乐趣:

      product = [*map(lambda x: [*map(lambda y: y * scalar, x)], A)]
      

      Try it online!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-03-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-06-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多