Python|连续自定义块元素产品
有许多方法可以用元素在列表中执行产品,但有时,它需要以切片的方式找到具有数字的列表的产品。这可以是自定义的,因此这方面的知识可以派上用场。让我们讨论一些可以做到这一点的方法。
方法 #1:使用列表理解 + enumerate()
+ 循环
列表推导可以完成可能的迭代部分,枚举可以帮助逻辑部分和检查列表中所需的有效元素。该循环用于执行产品。
# Python3 code to demonstrate
# Consecutive Custom Chunked elements Product
# using list comprehension + enumerate() + loop
# getting Product
def prod(val) :
res = 1
for ele in val:
res *= ele
return res
# initializing lists
test_list = list(range(1, 50))
# printing original list
print ("The original list is : " + str(test_list))
# interval elements
N = 5
# interval difference
K = 15
# using list comprehension + enumerate() + loop
# Consecutive Custom Chunked elements Product
res = prod([i for j, i in enumerate(test_list) if j % K < N ])
# printing result
print ("The modified range product list : " + str(res))
The original list is : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]
The modified range product list : 44225406378688905216000
方法#2:使用 itertools.compress() + itertools.cycle() + loop
上述两个函数可以结合起来,以方便解决所讨论的问题。循环函数可以用于重复任务,而压缩函数在将片段组合在一起时可能是有益的。该循环用于执行产品。
# Python3 code to demonstrate
# Consecutive Custom Chunked elements Product
# using itertools.compress() + itertools.cycle() + loop
from itertools import compress, cycle
# getting Product
def prod(val) :
res = 1
for ele in val:
res *= ele
return res
# initializing lists
test_list = list(range(1, 50))
# printing original list
print ("The original list is : " + str(test_list))
# interval elements
N = 5
# interval difference
K = 15
# using itertools.compress() + itertools.cycle() + loop
# Consecutive Custom Chunked elements Product
func = cycle([True] * N + [False] * (K - N))
res = prod(list(compress(test_list, func)))
# printing result
print ("The modified range product list : " + str(res))
The original list is : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]
The modified range product list : 44225406378688905216000