Python – 相似指数产品的行求和
给定一个矩阵和元素列表,对于每一行,提取元素与参数列表的乘积之和。
Input : test_list = [[4, 5], [1, 5], [8, 2]], mul_list = [5, 2, 3]
Output : [30, 15, 44]
Explanation : For 1st row, (4*5) + (5*2) = 30, as value of 1st element of result list. This way each element is computed.
Input : test_list = [[4, 5, 8, 2]], mul_list = [5, 2, 3, 9]
Output : [72]
Explanation : Similar computation as above method. Just 1 element as single Row.
方法#1:使用循环
这是解决此问题的蛮力方法。在此,我们执行每一行的迭代,并使用循环的蛮力方法在产品中执行所需的求和。
# Python3 code to demonstrate working of
# Row Summation of Like Index Product
# Using loop
# initializing list
test_list = [[3, 4, 5], [1, 7, 5], [8, 1, 2]]
# printing original list
print("The original list is : " + str(test_list))
# initializing mul list
mul_list = [5, 2, 3]
# Using loop
res = []
for sub in test_list:
sum = 0
for idx, ele in enumerate(sub):
# performing summation of product with list elements
sum = sum + (ele * mul_list[idx])
# adding each row sum
res.append(sum)
# printing result
print("List after multiplication : " + str(res))
输出 :
The original list is : [[3, 4, 5], [1, 7, 5], [8, 1, 2]]
List after multiplication : [38, 34, 48]
方法 #2:使用map() + sum() + zip() + lambda
上述功能的组合可以用来解决这个问题。在此,我们使用 sum() 执行求和任务,zip() 用于将乘法列表映射到行值,并使用 lambda 和 map() 对每一行及其元素进行封装和扩展的逻辑。
# Python3 code to demonstrate working of
# Row Summation of Like Index Product
# Using map() + sum() + zip() + lambda
# initializing list
test_list = [[3, 4, 5], [1, 7, 5], [8, 1, 2]]
# printing original list
print("The original list is : " + str(test_list))
# initializing mul list
mul_list = [5, 2, 3]
# Using map() + sum() + zip() + lambda
# Performing product in inner map, by zipping with elements list, and sum at outer map() used.
res = list(map(sum, (map(lambda ele: ([x * y for x, y in zip(
ele, mul_list)]), test_list))))
# printing result
print("List after multiplication : " + str(res))
输出 :
The original list is : [[3, 4, 5], [1, 7, 5], [8, 1, 2]]
List after multiplication : [38, 34, 48]