Python 程序:将字典中的所有项相乘

编写一个 Python 程序,通过实际示例将字典中的所有项相乘。

在此 Python 程序中,我们使用 For 循环来迭代字典中的每个元素。在 for 循环内部,我们将这些值与 total 变量相乘。

myDict = {'x': 20, 'y':5, 'z':60}
print("Dictionary: ", myDict)

total = 1
# Multiply Items
for key in myDict:
    total = total * myDict[key]
    
print("\nAfter Multiplying Items in this Dictionary: ", total)
Python Program to Multiply All Items in a Dictionary

Python 程序:将字典中的项相乘 示例 2

程序 使用 For 循环 以及 values 函数来乘以 字典 中的值。

myDict = {'x': 2, 'y':50, 'z':70}
print("Dictionary: ", myDict)

total = 1
# Multiply Items
for i in myDict.values():
    total = total * i
    
print("\nAfter Multiplying Items in this Dictionary: ", total)

乘法字典项输出

Dictionary:  {'x': 2, 'y': 50, 'z': 70}

After Multiplying Items in this Dictionary:  7000