Python – 列表字首乘積


Python 屬於高階語言,使用 Python 的人員可以使用簡單的概念和功能找到問題的解決方案。該語言由多種資料結構組成,其中列表是最常見的。列表中的元素可以是任何資料型別,例如整數、字串或浮點數型別。元素用方括號括起來,並用逗號分隔。使用列表資料結構是最有趣的基礎知識之一。

列表字首乘積

列表資料結構由整數元素組成,列印列表中字首的乘積涉及將第一個元素與第二個元素相乘,然後將其儲存在第一個索引位置的方法。

0

1

2

3

5

6

7

8

第一行表示索引值,第二行表示元素的值。第一個元素保留其位置。索引值 0 和 1 相乘後,結果儲存在第二個位置,該過程繼續進行。

第一個元素 = 5

第二個元素 = 5 * 6 = 30

第三個元素 = 30 * 3 = 210

第四個元素 = 210 * 8 = 1680

方法

  • 方法 1 - 使用使用者自定義函式。

  • 方法 2 - 使用 numpy 模組

  • 方法 3 - 使用 itertools 方法

方法 1:使用使用者函式定義列印列表中字首乘積的 Python 程式

該函式定義了列印字首元素乘積所需的引數。

演算法

  • 步驟 1 - 使用一個引數定義函式。

  • 步驟 2 - 初始化空列表和空變數,其值為 1。

  • 步驟 3 - for 迴圈將遍歷列表,另一個 for 迴圈將從當前索引值開始迭代。

  • 步驟 4 - 臨時變數乘以當前元素。

  • 步驟 5 - 然後,append 函式將新增乘法後的元素。

  • 步驟 6 - 使用 print 函式將相乘後的元素作為新列表返回。

示例

#Defining the function with the input of integer data type 
def pre_mul(list1):
#Creating an empty list
    result = []
#for loop is used to iterate through the list according to the range
    for num in range(0,len(list1)):
        temp = 1
        for val in range(num+1):
            temp *= list1[val]
        result.append(temp)
    return result
#list is initialized with elements
list1 = [5, 6 ,7 ,8]
#print function returns the list after the product of prefix
print(pre_mul(list1))

輸出

[5, 30, 210, 1680]

方法 2:使用 numpy 模組列印列表中字首乘積的 Python 程式

使用 numpy 模組中的名為“cumprod”的函式,按特定順序(從第一個元素到最後一個元素)相乘字首元素。

演算法

  • 步驟 1 - 匯入 numpy 模組以使用所需函式。

  • 步驟 2 - 建立列表資料結構以儲存整數值。

  • 步驟 3 - 使用 cumprod() 方法獲取列表中元素的累積乘積。

  • 步驟 4 - 結果儲存在名為“pro”的變數中。

  • 步驟 5 - 然後,print 函式將在執行字首乘積後返回列表。

示例

#Importing the numpy module
import numpy as np
#creating a list to hold the values of integer elements
list1 = [5, 6 ,7 ,8]
#pro variable is created to store the result after cumprod()
pro = np.cumprod(list1)
#return the new list
print(pro)

輸出

[   5   30  210 1680]

方法 3:使用 itertools 模組列印列表中字首乘積的 Python 程式

使用 itertools 模組中的函式列印字首的乘積。此模組通常用於最大限度地減少程式中迭代的複雜性。

演算法

  • 步驟 1 - 匯入 itertools 模組以使用名為 accumulate() 的函式。

  • 步驟 2 - 使用四個整型元素 [5, 6, 7, 8] 初始化列表。

  • 步驟 3 - 宣告一個新變數來儲存執行累積運算後的值。

  • 步驟 4 - 通常使用 lambda 函式,在不需要定義函式並且可以使用關鍵引數執行過程的情況下。

示例

#the required module is imported
import itertools
#list is initialized with integer elements
list1 = [5, 6 ,7 ,8]
#accumulate function to do the multiplication of the prefix elements
pro = list(itertools.accumulate(list1, lambda a,b: a*b))
#finally returns the final list
print(pro)

輸出

[5, 30, 210, 1680]

結論

列表資料結構(在方括號內)中定義的元素一旦定義就不能更改。為了列印列表資料結構中的字首乘積,Python 語言為使用者提供了一些內建功能。因此,在列表中,我們可以將多個值儲存在一起,從而減少複雜的操作。

更新於:2023年9月4日

瀏覽量 151

開啟您的 職業生涯

完成課程獲得認證

開始學習
廣告