Python – 累积记录产品
有时,在处理记录形式的数据时,我们可能会遇到一个问题,即我们需要找到收到的所有记录的产品元素。这是一个非常常见的应用程序,可以发生在数据科学领域。让我们讨论可以执行此任务的某些方式。
方法#1:使用循环+生成器表达式
这是实现此任务解决方案的最基本方法。在此,我们使用生成器表达式遍历整个嵌套列表,并使用显式产品函数获取产品元素。
Python3
# Python3 code to demonstrate working of
# Cumulative Records Product
# using loop + generator expression
# getting Product
def prod(val) :
res = 1
for ele in val:
res *= ele
return res
# initialize list
test_list = [(2, 4), (6, 7), (5, 1), (6, 10), (8, 7)]
# printing original list
print("The original list : " + str(test_list))
# Cumulative Records Product
# using loop + generator expression
res = prod(int(j) for i in test_list for j in i)
# printing result
print("The Cumulative product of list is : " + str(res))
Python3
# Python3 code to demonstrate working of
# Cumulative Records Product
# using product + map() + chain.from_iterable()
from itertools import chain
# getting Product
def prod(val) :
res = 1
for ele in val:
res *= ele
return res
# initialize list
test_list = [(2, 4), (6, 7), (5, 1), (6, 10), (8, 7)]
# printing original list
print("The original list : " + str(test_list))
# Cumulative Records Product
# using product + map() + chain.from_iterable()
res = prod(map(int, chain.from_iterable(test_list)))
# printing result
print("The cumulative product of list is : " + str(res))
输出
The original list : [(2, 4), (6, 7), (5, 1), (6, 10), (8, 7)]
The Cumulative product of list is : 5644800
方法 #2:使用循环 + map() + chain.from_iterable()
上述方法的组合也可用于执行此任务。其中,查找产品的扩展是通过 map() 和 from_iterable() 的组合来完成的。
Python3
# Python3 code to demonstrate working of
# Cumulative Records Product
# using product + map() + chain.from_iterable()
from itertools import chain
# getting Product
def prod(val) :
res = 1
for ele in val:
res *= ele
return res
# initialize list
test_list = [(2, 4), (6, 7), (5, 1), (6, 10), (8, 7)]
# printing original list
print("The original list : " + str(test_list))
# Cumulative Records Product
# using product + map() + chain.from_iterable()
res = prod(map(int, chain.from_iterable(test_list)))
# printing result
print("The cumulative product of list is : " + str(res))
输出
The original list : [(2, 4), (6, 7), (5, 1), (6, 10), (8, 7)]
The cumulative product of list is : 5644800