寫一個 Python 程序,用一個實際的例子找到字典中項目的總和。
在字典中查找項目總和的 Python 程序示例 1
在這個程序中我們使用的是求和函數,字典值函數求字典值的和。 Python sum 函數是返回一個字典 中所有值的總和
# Python Program to find Sum of Items in a Dictionary
myDict = {'x': 250, 'y':500, 'z':410}
print("Dictionary: ", myDict)
# Print Values using get
print("\nSum of Values: ", sum(myDict.values()))
計算字典中項目總和的 Python 程序示例 2
這個 Python 程序使用 For 循環和值函數在字典中添加值。
myDict = {'x': 250, 'y':500, 'z':410}
print("Dictionary: ", myDict)
total = 0
# Print Values using get
for i in myDict.values():
total = total + i
print("\nThe Total Sum of Values : ", total)
Python 字典項輸出的總和
Dictionary: {'x': 250, 'y': 500, 'z': 410}
The Total Sum of Values : 1160
計算字典中所有項目總和的 Python 程序示例 3
在這個 Python 程序中,我們使用 For Loop 來迭代這個字典中的每個元素。在 Python 循環中,我們將這些字典值添加到總變數中。
myDict = {'x': 250, 'y':500, 'z':410}
print("Dictionary: ", myDict)
total = 0
# Print Values using get
for i in myDict:
total = total + myDict[i]
print("\nThe Total Sum of Values : ", total)
Dictionary: {'x': 250, 'y': 500, 'z': 410}
The Total Sum of Values : 1160
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/227875.html