Python|不均匀尺寸矩阵柱产品
与传统的 C 类型 Matrix 不同,通常的列表列表可以允许具有可变长度的列表的嵌套列表,并且当我们需要其列的乘积时,行的不均匀长度可能会导致该元素中的某些元素不存在,并且如果处理不当,可能会抛出异常。让我们讨论一些可以以无错误方式执行此问题的方法。
方法 #1:使用循环 + filter() + map()
+ 列表理解
上述三个函数与列表推导相结合可以帮助我们执行这个特定任务,外部 prod函数有助于执行乘法,filter 允许我们检查当前元素,所有行都使用 map函数组合。仅适用于Python 2。
# Python code to demonstrate
# Uneven Sized Matrix Column product
# using loop + filter() + map() + list comprehension
# getting Product
def prod(val) :
res = 1
for ele in val:
res *= ele
return res
# initializing list of lists
test_list = [[1, 5, 3], [4], [9, 8]]
# printing original list
print ("The original list is : " + str(test_list))
# using loop + filter() + map() + list comprehension
# Uneven Sized Matrix Column product
res = [prod(filter(None, j)) for j in map(None, *test_list)]
# printing result
print ("The product of columns is : " + str(res))
输出 :
The original list is : [[1, 5, 3], [4], [9, 8]]
The product of columns is : [36, 40, 3]
方法 #2:使用列表理解 + 循环 + zip_longest()
如果不想使用 None 值,可以选择这种方法来解决这个特定问题。 zip_longest函数有助于用 1 填充不存在的列,这样它就不必处理不存在的元素的空白。
# Python3 code to demonstrate
# Uneven Sized Matrix Column product
# using list comprehension + loop + zip_longest()
import itertools
# getting Product
def prod(val) :
res = 1
for ele in val:
res *= ele
return res
# initializing list of lists
test_list = [[1, 5, 3], [4], [9, 8]]
# printing original list
print ("The original list is : " + str(test_list))
# using list comprehension + loop + zip_longest()
# Uneven Sized Matrix Column product
res = [prod(i) for i in itertools.zip_longest(*test_list, fillvalue = 1)]
# printing result
print ("The product of columns is : " + str(res))
输出 :
The original list is : [[1, 5, 3], [4], [9, 8]]
The product of columns is : [36, 40, 3]