📜  Python|乘以相邻元素

📅  最后修改于: 2022-05-13 01:54:57.913000             🧑  作者: Mango

Python|乘以相邻元素

有时,在处理数据时,我们可能会遇到需要找到累积结果的问题。这可以是任何类型、乘积或总和。在这里,我们将讨论相邻元素的乘法。让我们讨论可以执行此任务的某些方式。

方法 #1:使用zip() + 生成器表达式 + tuple()
上述功能的组合可用于执行此任务。在此,我们使用生成器表达式来提供乘法逻辑,同时元素配对由zip()完成。使用tuple()将结果转换为元组形式。

# Python3 code to demonstrate working of
# Adjacent element multiplication
# using zip() + generator expression + tuple
  
# initialize tuple
test_tup = (1, 5, 7, 8, 10)
  
# printing original tuple
print("The original tuple : " + str(test_tup))
  
# Adjacent element multiplication
# using zip() + generator expression + tuple
res = tuple(i * j for i, j in zip(test_tup, test_tup[1:]))
  
# printing result
print("Resultant tuple after multiplication : " + str(res))
输出 :
The original tuple : (1, 5, 7, 8, 10)
Resultant tuple after multiplication : (5, 35, 56, 80)

方法 #2:使用tuple() + map() + lambda
上述功能的组合也可以帮助执行此任务。在此,我们使用 lambda函数执行乘法和绑定逻辑。 map()用于迭代每个元素,最终结果由tuple()转换。

# Python3 code to demonstrate working of
# Adjacent element multiplication
# using tuple() + map() + lambda
  
# initialize tuple
test_tup = (1, 5, 7, 8, 10)
  
# printing original tuple
print("The original tuple : " + str(test_tup))
  
# Adjacent element multiplication
# using tuple() + map() + lambda
res = tuple(map(lambda i, j : i * j, test_tup[1:], test_tup[:-1]))
  
# printing result
print("Resultant tuple after multiplication : " + str(res))
输出 :
The original tuple : (1, 5, 7, 8, 10)
Resultant tuple after multiplication : (5, 35, 56, 80)