在本教程中,我們將學習如何在 Python 中乘法列表的所有元素。
讓我們看一些例子來理解我們的目標-
Input - [2, 3, 4]
Output - 24
我們可以觀察到,在輸出中,我們獲得了列表中所有元素的乘積。
Input - [3, 'a']
Output - aaa
因為第一個元素是三,所以在輸出中會列印三次。
我們將學習以下方法-
- 遍歷列表
- 使用 NumPy
- 使用λ
讓我們從第一個開始,
遍歷列表
考慮下面給出的程序-
#creating a function
def multiply_ele(list_value1):
#multiply the elements
prod=1
for i in list_value1:
prod = prod*i
return prod
#initializing the list
list_value1 = [10, 11, 12, 13, 14]
list_value2 = [2, 3, 4, 5, 6, 7]
#displaying the resultant values
print("The multiplication of all the elements of list_value1 is: ", multiply_ele(list_value1))
print("The multiplication of all the elements of list_value2 is: ", multiply_ele(list_value2))
輸出:
The multiplication of all the elements of list_value1 is: 240240
The multiplication of all the elements of list_value2 is: 5040
解釋-
是時候看看上面程序的解釋了-
- 在第一步中,我們創建了一個函數,它將列表作為輸入。
- 在函數定義中,我們使用了一個
for
循環,該循環從列表中取出每個元素,最初將其乘以 1,然後輸出乘積的結果值。 - 在下一步中,我們已經初始化了列表,然後將它們傳遞給我們的函數。
- 執行該程序時,會顯示所需的輸出。
在第二個程序中,我們將看到 NumPy 如何幫助我們實現同樣的功能。
使用 NumPy
下面的程序說明了如何用 Python 來實現。
#importing the NumPy module
import numpy
#initializing the list
list_value1 = [10, 11, 12, 13, 14]
list_value2 = [2, 3, 4, 5, 6, 7]
#using numpy.prod()
res_list1 = numpy.prod(list_value1)
res_list2 = numpy.prod(list_value2)
#displaying the resultant values
print("The multiplication of all the elements of list_value1 is: ", res_list1)
print("The multiplication of all the elements of list_value2 is: ", res_list2)
輸出:
The multiplication of all the elements of list_value1 is: 240240
The multiplication of all the elements of list_value2 is: 5040
解釋-
讓我們了解一下我們在上面的程序中做了什麼。
- 第一步,我們已經導入了 NumPy 模塊。
- 在下一步中,我們已經初始化了兩個列表的值,list_value1 和 list_value2。
- 之後,我們將使用 prod() 計算列表中元素的乘積。
- 在執行程序時,會顯示預期的輸出。
最後,我們將學習如何使用 lambda 來相乘我們列表中的元素。
使用λ
下面給出的程序展示了相同的-
#importing the module
from functools import reduce
#initializing the list
list_value1 = [10, 11, 12, 13, 14]
list_value2 = [2, 3, 4, 5, 6, 7]
#using numpy.prod()
res_list1 = reduce((lambda a, b:a*b), list_value1)
res_list2 = reduce((lambda a, b:a*b), list_value2)
#displaying the resultant values
print("The multiplication of all the elements of list_value1 is: ", res_list1)
print("The multiplication of all the elements of list_value2 is: ", res_list2)
輸出:
The multiplication of all the elements of list_value1 is: 240240
The multiplication of all the elements of list_value2 is: 5040
解釋-
讓我們了解一下在上面的程序中發生了什麼。
- 第一步,我們從
- 之後,我們初始化了兩個列表, list_value1 和 list_value2 。
- 我們使用了定義函數的精確方式,即 lambda,然後提供了所需的功能。
- 在執行程序時,會顯示所需的值。
結論
在本教程中,我們學習了用 Python 將列表中的元素相乘的各種方法。
原創文章,作者:T0NS3,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/127974.html