Python字典值乘以常數


開發者更傾向於使用Python語言而不是其他程式語言,因為它簡單易用且功能多樣。它包含各種內建資料結構,其中之一是字典,可以儲存鍵值對元素。字典資料結構中的元素用逗號分隔,並用花括號“{}”括起來。字典不遵循任何元素順序,並且分配的鍵值不可更改。字典可以儲存列表、元組或其他字典等元素。

Python字典值乘以常數

可以使用該語言提供的各種內建函式輕鬆操作字典。其中一個有用的函式是將Python字典值乘以常數。字典的基本語法是:

Dict_1 = {‘John’: ‘number’, ‘Bye’: 453}

很多時候我們需要調整Python字典中存在的數值,將字典值乘以常數就是這樣一個場景,這個功能非常有用。此外,由於Python提供了多種使用NumPy或Pandas等內建庫以及許多其他第三方庫來最佳化記憶體利用率的選項,因此我們可以輕鬆有效地對更大的資料集執行資料縮放。

總之,Python字典是程式語言中儲存鍵值對的一種好方法,可以透過簡單的常數因子乘法來輕鬆縮放值,方法是遍歷字典中的項或利用Python相容的不同科學計算庫中提供的先進最佳化技術。

方法

  • 方法一 - 使用迭代方法

  • 方法二 - 使用numpy模組

方法一:使用迭代方法將字典值乘以常數的Python程式

只需使用for迴圈即可將常數與字典值相乘。處理小型字典集時推薦使用此方法,但對於大型資料集,此方法無效。

演算法

  • 字典集用值和鍵值初始化。

  • 然後使用print函式列印給定的輸入。

  • 根據使用者需求定義縮放因子,在本例中為3。

  • for迴圈將迭代給定字典的每個元素,然後將其與常數相乘。

  • 乘法後,輸出作為字典集返回。

示例

# Initializing the dictionary data structure
dict1 = {'Tomato': 10, 'Carrot':20,'Beans':30}
print("Given Dictionary set is : ", dict1) 

# Adding a new key-value pair to the dictionary
dict1['radish'] = 40

# Multiplying the above dictionary with a constant value of 5
constant_value = 3

# Using get()
# Multiply Dictionary Value by Constant
for key in dict1:
    dict1[key] = dict1.get(key) * constant_value

# Final statement after multiplying with constant      
print("Dictionary value after multiplication is:",dict1)

輸出

Given Dictionary set is :  {'Tomato': 10, 'Carrot': 20, 'Beans': 30}
Dictionary value after multiplication is: {'Tomato': 30, 'Carrot': 60, 'Beans': 90, 'radish': 120}

方法二:使用numpy模組將字典值乘以常數的Python程式

numpy模組用於透過將給定的字典轉換為numpy陣列,然後使用乘法函式執行運算來將常數乘以字典值。

演算法

  • 匯入numpy庫。

  • 建立包含三個值和鍵的字典。

  • 初始化需要乘以的常數。

  • Numpy模組將透過將相同的值乘以常數來建立一個新的字典。

  • print函式返回所需的輸出。

示例

#importing the module
import numpy as np

# Initializing the dictionary data structure
dict1 = {'Tomato': 10, 'Carrot':20,'Beans':30}
print("Given Dictionary set is : ", dict1) 

# Adding a new key-value pair to the dictionary
dict1['radish'] = 40

# Multiplying the above dictionary with a constant value of 3 using numpy
constant_value = 3

dict1 = {k: np.multiply(v, constant_value) for k, v in dict1.items()}

# Final statement after multiplying with constant      
print("Dictionary value after multiplication is:",dict1)

輸出

Given Dictionary set is :  {'Tomato': 10, 'Carrot': 20, 'Beans': 30}
Dictionary value after multiplication is: {'Tomato': 30, 'Carrot': 60, 'Beans': 90, 'radish': 120}

結論

Python程式設計有助於簡化複雜的功能。乘法似乎是簡單的計算,但是對於大型資料集,我們需要使用Python語言中的一些內建函式,例如numpy或pandas。當使用“for迴圈”執行上述操作時,會導致記憶體密集型操作,甚至可能導致程式碼崩潰。

更新於:2023年9月1日

827 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始
廣告