Python – 列表中第 k 列的乘積


列表可以在方括號內包含任意數量的子列表,子列表之間用逗號分隔。一旦在方括號內的列表資料結構中定義了元素,就不能更改它們。因此,在列表中,我們可以將多個值儲存在一起,從而減少複雜的運算。列表可以包含元素和另一個稱為子列表的列表。

在這篇文章中,我們將介紹如何將列元素相乘,為了更好地理解,讓我們來看一個例子。該列表包含三個子列表,每個子列表包含三個元素。程式設計師決定計算每個列表的最後一個元素(索引值為 2)的所有元素的乘積。

List = [[1, 2, 3],
	[4, 5, 6],
	[7, 8, 9]]

將第二個索引元素相乘,即 3*6*9 = 162 是返回的乘積。同樣,Python 程式使用不同的方法執行這些功能,從而提高效率並減少時間。

方法

  • 方法 1 − 使用 for 迴圈

  • 方法 2 − 使用 reduce 方法

方法 1:使用 for 迴圈計算列表中列表的第 k 列的乘積的 Python 程式

for 迴圈將遍歷給定的元素列表,並找到列表中列表的指定索引值的乘積。

演算法

  • 步驟 1 − 使用兩個引數定義函式

  • 步驟 2 − 使用 isinstance(),我們可以檢查給定的輸入是否存在於列表中。

  • 步驟 3 − 在下面的程式碼中,它被指定為 2,因此列印結果;另一方面,當指定的值大於 2 時,它將執行 return 語句。

  • 步驟 4 − 然後它檢查三行(三個列表)是否具有足夠的且相等的列。

  • 步驟 5 − 使用 for 迴圈計算乘積值並將其儲存在名為“result”的變數中

  • 步驟 6 − 列表用整數和三個子列表初始化。

  • 步驟 7 − 列印最終輸出。

示例

#function is defined with two parameters
def product_cols(lst,cols_val):
    #To check whether the input is in the given list
    if not isinstance(lst,list):
        raise Exception(f"object {type(file)} isn't list type")
    
    #if loop is used to check whether all column and indexes are correct
    for a,row in enumerate(lst,start=1):
        try:
            temp=row[cols_val]
        except IndexError:
            raise Exception(f"{str(a)}th given values is not within the limit{str(cols_val)}.")           
              
    # The product is calculated using for loop
    result = 1
    for each_row in lst:
        result *= each_row[cols_val]
        
    return result
#initializing the list element
list1 = [[1, 2, 3], 
           [4, 5, 6], 
           [7, 8, 9]]
#The final output is printed for the elements in index value of 2
print(product_cols(list1, 2))

輸出

162

方法 2:使用 reduce() 方法計算列表中列表的第 k 列的乘積的 Python 程式

這個過程看起來很簡單,但是使用 reduce 方法實現程式比較繁瑣。匯入所需的模組,並根據給定的輸入值執行程式。

演算法

  • 步驟 1 − 匯入所需的模組以使用 reduce 和 operator 等函式。

  • 步驟 2 − 使用列表的列表和列索引值作為兩個引數定義函式。

  • 步驟 3 − 檢查輸入,判斷它是否存在於給定的列表中。

  • 步驟 4 − 然後檢查行是否正確地包含所有列元素。

  • 步驟 5 − 在 reduce 函式的幫助下,計算列表中列表的乘積,並使用 print() 函式返回結果。

示例

#importing the module to use reduce function
from functools import reduce
#importing the operator
import operator
#defining the function with two parameters
def product_cols(lst,cols_val):
#To check whether the input is in the given list
    if not isinstance(lst,list):
        raise Exception(f"object {type(file)} isn't list type")
    
    #if loop is used to check whether all column and indexes are correct
    for a,row in enumerate(lst,start=1):
        try:
            temp=row[cols_val]
        except IndexError:
            raise Exception(f"{str(a)}the given values is not within the limit{str(cols_val)}.")           
              
    return reduce(operator.mul,[each_row[cols_val] for each_row in lst])
#initializing the list with set of sublists
list1 = [[1, 2, 3], 
           [4, 5, 6], 
           [7, 8, 9]]
#Finally printing the list after the multiplication
print(product_cols(list1, 2))

輸出

162

結論

Python 屬於高階語言,使用 Python 的人員可以使用簡單的概念和功能找到問題的解決方案。該語言由多種資料結構組成,其中列表是最常見的。本文介紹了使用 functools 模組和 for 迴圈方法計算第 k 列乘積的不同方法。

更新於:2023年9月4日

73 次瀏覽

啟動您的職業生涯

完成課程獲得認證

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