簡體   English   中英

Python - 將 for 循環變成單行循環

[英]Python - Turning a for-loop into a one-liner

我正在嘗試創建一個矩陣乘法標量函數,沒有任何庫。 它必須包括列表理解:

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)

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

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

在線試試吧!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM