Python - 索引匹配元素乘積
索引匹配元素乘積指的是兩個不同的列表,其中包含元素並分別設定為相應的變數。如果找到公共匹配項,則透過乘法過濾元素。為了解決這個問題,Python 有一些內建函式,例如 range()、len()、zip()、prod()、reduce() 和 lambda()。
讓我們來看一個例子。
給定的輸入列表
list_1 = [10, 20, 30, 40]
list_2 = [10, 29, 30, 10]
因此,在索引 0 和 2 中找到的公共匹配項,其乘積為 10*30 = 300。
語法
以下語法在示例中使用
range()
range() 是 Python 中的內建函式,它根據給定的範圍返回數字序列。
len()
len() 是 Python 中的內建函式,它返回物件的長度。
zip()
內建函式
prod()
prod() 是 Python 中的內建函式,它返回所有元素的乘積。
reduce()
reduce 是 Python 中的內建方法,它遵循 functools 模組,透過接受兩個引數(函式和可迭代物件)來返回單個值。
lambda()
lambda 函式提供了一種使用 lambda 關鍵字宣告簡短匿名函式的快捷方式。lambda 函式只有一個表示式。
使用 for 迴圈
在下面的示例中,我們將透過在各自的變數中建立兩個列表來啟動程式。然後將初始值 p 設定為 1,這將用於與列表元素的乘積。接下來,使用 for 迴圈使用內建函式 len() 迭代第一個輸入列表。使用 if 語句,它檢查第一個列表的索引是否與第二個列表的索引匹配。如果找到公共匹配項,則透過乘以 1 來過濾這些列表元素,從而簡化輸出。
示例
lst1 = [10, 20, 30, 40, 50, 60] lst2 = [10, 34, 3, 89, 7, 60] p = 1 for i in range(len(lst1)): if lst1[i] == lst2[i]: p *= lst1[i] print("Result of index match element Product:\n", p)
輸出
Result of index match element Product: 600
使用列表推導式和 zip() 函式
在下面的示例中,程式使用列表推導式,其中 zip() 方法將兩個不同的列表組合在一起以查詢公共匹配項。如果兩個列表中的公共元素匹配,則它透過對這些元素進行乘積來返回過濾結果。
示例
# Using list comprehension and zip() lst1 = [10, 20, 30, 40, 50, 60] lst2 = [10, 34, 30, 89, 7, 60] # Initialize the initial value of the Product product = 1 match_item = [x for x, y in zip(lst1, lst2) if x == y] # Using if-statement to iterate the matching element if match_item: product = 1 for element in match_item: product *= element print("Result of index match element Product:\n", product)
輸出
Result of index match element Product: 18000
使用 Numpy 庫
在下面的示例中,程式使用 numpy 庫和物件引用作為 np。然後建立兩個列表,這些列表將用於查詢公共索引元素。接下來,將列表轉換為各自變數中的陣列,這將用作元素陣列。現在,從兩個陣列中找到公共索引元素,並使用 prod() 將所有公共元素相乘並顯示結果。
示例
import numpy as np # create the list lst1 = [10, 20, 30, 40, 50, 60] lst2 = [10, 34, 30, 89, 50, 6] # Convert the list into an array arr1 = np.array(lst1) arr2 = np.array(lst2) # Set the condition for matching element match_item = arr1[arr1 == arr2] prod_idx = np.prod(match_item) # Display the result print("Result of index match element Product:\n", prod_idx)
輸出
Result of index match element Product: 15000
使用 Functools 庫
pip install functools
上述所需的命令對於在系統上安裝以執行基於 functools 的特定程式是必要的。
在下面的示例中,使用 functools 庫啟動程式,並定義名為 reduce 的模組,該模組將計算索引匹配元素。然後使用列表推導式,其中 zip() 函式包含兩個列表以設定等效條件以查詢公共匹配項。接下來,使用一些內建函式 - reduce()、lambda 和 if - 設定基於匹配元素乘積的條件。最後,顯示結果。
示例
from functools import reduce # Create the list lst1 = [10, 20, 30, 40, 7, 60] lst2 = [10, 34, 30, 89, 7, 60] # Set the condition based on the matching element matching_elements = [x for x, y in zip(lst1, lst2) if x == y] prod_idx = reduce(lambda x, y: x * y, matching_elements) if matching_elements else 1 # display the product print("Result of index match element Product:\n", prod_idx)
輸出
Result of index match element Product: 126000
結論
索引匹配元素是可以使用某些特定條件和操作(例如 numpy 庫、functools 庫、列表推導式和 for 迴圈)進行過濾的公共元素。此程式有一些相關的應用程式,例如資料分析和資料過濾。