![](/img/trans.png)
[英]Why is the syntax invalid in this Python one-liner using a for-loop?
[英]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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.