Python - 字典中元組值的乘積


Python 中的字典被廣泛用於以鍵值對的形式儲存資料。很多時候,我們會遇到需要查詢字典中作為值的元組中元素的乘積的情況。這種情況通常發生在處理資料操作或分析時。透過本文,我們將編寫程式碼並瞭解解包字典和計算每個索引處元組元素乘積的各種方法。

輸入

{'a': (1, 3, 5, 7), 'b': (2, 4, 6, 8), 'c': (2, 3, 5, 7)}

輸出

(4, 36, 150, 392)

方法 1:使用元組解包和 zip() 函式

在這種方法中,我們將嘗試從字典中獲取元組並對其進行解包以獲取乘積。然後,透過 zip() 將相同索引的值組合在一起,我們能夠生成元組中每個元素的乘積。

示例

# Define a function to calculate the product of elements in a tuple
def prodTup(inp):
   out = 1
   for item in inp:
      out *= item
   return out

# Create a dictionary with tuples as values
inpDict = {'a': (1, 3, 5, 7), 'b': (2, 4, 6, 8), 'c': (2, 3, 5, 7)}

# Print the input dictionary
print("Input Dictionary: " + str(inpDict))

# Calculate the product of elements at the same indices across the tuples
result = tuple(prodTup(ele) for ele in zip(*inpDict.values()))

# Print the calculated products
print("Output: " + str(result))

輸出

Input Dictionary: {'a': (1, 3, 5, 7), 'b': (2, 4, 6, 8), 'c': (2, 3, 5, 7)}
Output: (4, 36, 150, 392)

因此,我們解包了字典,並且只保留了值。Zip 幫助我們將作為值的元組括起來,因此乘積函式會迭代這些括起來的元素。最終輸出如預期。

方法 2:使用元組解包和 map() 函式

map 函式將幫助我們在元組上迭代乘積函式。元組可以被解包並排列,以便我們可以對映乘積。這可以透過迴圈和列表輕鬆完成。

示例

# getting Product
def prodTup(inp):
   res = 1
   for ele in inp:
      res *= ele
   return res

# Create a dictionary with tuples as values
inpDict = {'a': (1, 3, 5, 7), 'b': (2, 4, 6, 8), 'c': (2, 3, 5, 7)}

# Print the input dictionary
print("Input Dictionary: " + str(inpDict))

# Using tuple unpacking for transposing
tempList = [list(sub) for sub in inpDict.values()]
transposedTempList = [tuple(row[i] for row in tempList) for i in range(len(tempList[0]))]
result = tuple(map(prodTup, transposedTempList))

# Printing the result
print("Output: ", result)

輸出

Input Dictionary: {'a': (1, 3, 5, 7), 'b': (2, 4, 6, 8), 'c': (2, 3, 5, 7)}
Output:  (4, 36, 150, 392)

因此,我們使用了元組解包來獲取轉置形式,以便正確地對映元組中的索引元素,以便乘積函式能夠透過 map 進行迭代。儘管程式碼變得有點長,但可以進行最佳化。

方法 3:利用 map()、lambda 和 reduce()

現在讓我們嘗試生成所需的輸出,但不是使用迴圈來迭代乘積函式,而是使用 map()、lambda,它可以幫助我們在可迭代物件上執行函式。reduce() 方法將用於乘積函式。

示例

import operator
from functools import reduce

def calculatePro(tuples_dict):
   return tuple(map(lambda *args: reduce(operator.mul, args), *tuples_dict.values()))

inputDict = {'a': (1, 3, 5, 7), 'b': (2, 4, 6, 8), 'c': (2, 3, 5, 7)}
print("Input list: " + str(inputDict))

result = calculatePro(inputDict)

print("Output: " + str(result))

輸出

Input list: {'a': (1, 3, 5, 7), 'b': (2, 4, 6, 8), 'c': (2, 3, 5, 7)}
Output: (4, 36, 150, 392)

一個簡單的單行返回函式實際上計算了乘積,正如我們所看到的。我們用 lambda 傳遞 map,它可以幫助我們迭代字典中的每個元組值。

然後,reduce() 函式可以透過 operator.mul 函式按索引迭代元組的每個元素以獲取輸出。

方法 4:使用列表推導式和 numpy.prod()

列表推導式在許多問題中被大量使用。就像我們必須迭代和解包元組一樣,在最後三種方法中,列表推導式將在這裡幫助我們。讓我們迭代字典中所需索引處的元組。numpy 庫的 prod 方法將計算乘積。

示例

import numpy as np

# dictionary with tuples as values
inputDict = {'a': (1, 3, 5, 7), 'b': (2, 4, 6, 8), 'c': (2, 3, 5, 7)}

# the original dictionary
print("Input dictionary: ", inputDict)

result = tuple(np.prod([inputDict[key][i] for key in inputDict]) for i in range(len(inputDict[list(inputDict.keys())[0]])))

# result
print("Output: ", result)

輸出

Input dictionary:  {'a': (1, 3, 5, 7), 'b': (2, 4, 6, 8), 'c': (2, 3, 5, 7)}
Output:  (4, 36, 150, 392)

因此,我們迭代了字典值中元組的每個索引。然後,我們使用列表和列表推導式來迭代所有匹配的索引。最後,prod 給我們乘積。

方法 5:使用遞迴方法

遞迴方法也可用於計算每個索引處元組元素的乘積。儘管對於較大的資料集而言,這種方法可能不是最有效的,但它對於教育目的很有用。

示例

def prodTup(inp):
   res = 1
   for ele in inp:
      res *= ele
   return res

def recursive_product(tuples_dict, index=0):
   if index >= len(next(iter(tuples_dict.values()))):
      return ()
   return (prodTup(tuple(tuples_dict[key][index] for key in tuples_dict)),) + recursive_product(tuples_dict, index + 1)

inputDict = {'a': (1, 3, 5, 7), 'b': (2, 4, 6, 8), 'c': (2, 3, 5, 7)}
result = recursive_product(inputDict)
print("Output: ", result)

輸出

Output:  (4, 36, 150, 392)

結論

根據索引獲取儲存在 Python 字典中作為值的元組元素的乘積,可以使用上面討論的各種方法來實現。每種方法都提供了實現所需結果的方法,根據特定需求或邊界提供靈活性和選擇。因此,始終為更多方法的出現留有廣闊的空間。

重要的是要理解每種方法的實現和邏輯,以便迭代字典值作為元組,然後迭代元組本身。必須將正確的索引與其值對映起來才能實現乘積。

更新於: 2023年11月2日

132 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.