Python程式:如何計算列表中所有數字的乘積?


本文將介紹幾種在 Python 中計算列表中所有數字乘積的方法。列表是一個有序的值集合,用方括號括起來。列表包含稱為專案的值,可以透過其唯一的索引檢索。

所有值的乘積是一個單一的值。例如,對於列表 [3,2,6],結果將是 36。我們將介紹幾種計算列表中所有數字乘積的方法。

使用 math.prod() 函式

這種方法使用 math 模組的 prod() 函式計算乘積。在我們的程式中,math 模組為使用者提供了許多數學運算,包括 pow()、sum() 和 avg()。

演算法

以下是使用 math.prod() 函式計算列表中所有數字乘積的方法:

  • 匯入模組。

  • 定義一個用於數字相乘的函式。

  • 然後返回 math.prod(list)。

  • 建立一個列表。

  • 呼叫函式並傳遞列表。

  • 列印函式返回的值。

示例

以下是使用 math.prod() 函式計算列表中所有數字乘積的示例:

#importing math module import numpy def multiply_numbers(list): return numpy.prod(list) given_list = [2,5,3,7,4,85,-3] print('The list is:',given_list) print("The product is: ") print(multiply_numbers(given_list))

輸出

以下是上述程式碼的輸出:

The list is: [2, 5, 3, 7, 4, 85, -3]
The product is: 
-214200

使用 numpy.prod() 函式

這種方法使用 NumPy 模組的 prod() 函式計算乘積。它允許程式設計師處理大量資料和許多高階數學計算。

演算法

以下是使用 numpy.prod() 函式計算列表中所有數字乘積的方法:

  • 匯入模組。
  • 定義一個用於數字相乘的函式。
  • 然後返回 numpy.prod(list)。
  • 建立一個列表。
  • 呼叫函式並傳遞列表。
  • 列印函式返回的值。

示例

以下是使用 numpy.prod() 函式計算列表中所有數字乘積的示例:

#importing math module import numpy def multiply_numbers(list): return numpy.prod(list) given_list = [2,1,3,7,4,85,3] print('The list is:',given_list) print("The product is: ") print(multiply_numbers(given_list))

輸出

以下是上述程式碼的輸出:

The list is: [2, 1, 3, 7, 4, 85, 3]
The product is: 
42840

使用 for 迴圈

在這種方法中,我們將遍歷整個列表直到找到該專案。為了得到結果,列表中的每個整數都應該乘以一個初始化為 1 的變數 product。我們將使用 Python 語言的 for 迴圈來訪問列表中的每個整數。

演算法

以下是使用 for 迴圈計算列表中所有數字乘積的方法:

  • 定義一個用於數字相乘的函式。
  • 宣告一個變數 product 並將其設定為 1。
  • 對列表中的每個元素執行迴圈。
  • 將每個元素乘以 product。
  • 返回 product。
  • 建立一個列表。
  • 透過我們的函式傳遞列表。
  • 列印函式返回的值。

示例

以下是使用 for 迴圈計算列表中所有數字乘積的示例:

def multiply_numbers(list): prod = 1 for i in list: prod = prod*i return prod given_list = [2,1,3,7,4,85,3] print('The list is:',given_list) print("The product is: ") print(multiply_numbers(given_list))

輸出

以下是上述程式碼的輸出:

The list is: [2, 1, 3, 7, 4, 85, 3]
The product is: 
42840

使用 reduce() 函式

可以匯入 functools 包中的 reduce() 方法。它接受三個引數:一個函式、一個序列和一個初始值[可選]。

它首先將函式傳遞給從序列中獲取的兩個資料項。該函式接收穫得的結果以及第三個資料項。這個過程重複進行,直到迭代器中沒有更多資料項。

示例

使用 lambda 函式

下面的示例計算列表中每個元素的乘積。Reduce() 接受 list_1 作為引數和一個 lambda 函式 (lambda m, n: m * n)。

lambda 函式接收給定列表的元素作為引數。lambda 函式在將引數相乘後返回 product 值。reduce() 函式的輸出是一個單一的值。

from functools import reduce given_list = [2,1,3,2,4,8,3] print('The list is:',given_list) product= print('The list is:',reduce((lambda m, n: m*n), given_list))

輸出

以下是上述程式碼的輸出。

The list is: [2, 1, 3, 2, 4, 8, 3]
The list is: 1152

使用 mul() 函式

示例

在我們使用 operator 模組的 mul() 函式將列表的所有值相乘之前,必須先匯入 operator 模組。

from operator import* given_list = [2,-3,3,2,4,5,3] print('The list is:',given_list) p = 1 for i in given_list: # multiply all the elements in the given list p = mul(i, p) print(p)

輸出

以下是上述程式碼的輸出:

The list is: [2, -3, 3, 2, 4, 5, 3]
-2160

更新於:2022年11月23日

24K+ 瀏覽量

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.