Python|矩阵产品
获取列表的乘积是一个很常见的问题,已经被处理和讨论过很多次,但有时,我们需要更好地获取列表的乘积,即包括嵌套列表的乘积。让我们尝试获得全部产品并解决这个特定问题。
方法#1:使用列表理解+循环
我们可以使用列表推导来解决这个问题,作为我们可以用来执行这个特定任务的传统循环的潜在速记。我们只是对嵌套列表进行迭代和乘积,最后使用函数返回累积乘积。
# Python3 code to demonstrate
# Matrix Product
# Using list comprehension + loop
# getting Product
def prod(val) :
res = 1
for ele in val:
res *= ele
return res
# initializing list
test_list = [[1, 4, 5], [7, 3], [4], [46, 7, 3]]
# printing original list
print("The original list : " + str(test_list))
# using list comprehension + loop
# Matrix Product
res = prod([ele for sub in test_list for ele in sub])
# print result
print("The total element product in lists is : " + str(res))
输出 :
The original list : [[1, 4, 5], [7, 3], [4], [46, 7, 3]]
The total element product in lists is : 1622880
方法#2:使用chain()
+循环
这个特殊问题也可以使用链函数而不是列表推导来解决,在列表推导中,我们使用常规函数来执行乘积。
# Python3 code to demonstrate
# Matrix Product
# Using chain() + loop
from itertools import chain
# getting Product
def prod(val) :
res = 1
for ele in val:
res *= ele
return res
# initializing list
test_list = [[1, 4, 5], [7, 3], [4], [46, 7, 3]]
# printing original list
print("The original list : " + str(test_list))
# using chain() + loop
# Matrix Product
res = prod(list(chain(*test_list)))
# print result
print("The total element product in lists is : " + str(res))
输出 :
The original list : [[1, 4, 5], [7, 3], [4], [46, 7, 3]]
The total element product in lists is : 1622880