成都网站建设设计

将想法与焦点和您一起共享

Python 程序:计算字典中项目的和

创新互联python教程:

为杭锦等地区用户提供了全套网页设计制作服务,及杭锦网站建设行业解决方案。主营业务为网站建设、成都做网站、杭锦网站设计,以传统方式定制建设网站,并提供域名空间备案等一条龙服务,秉承以专业、用心的态度为用户提供真诚的服务。我们深信只要达到每一位用户的要求,就会得到认可,从而选择与我们长期合作。这样,我们也可以走得更远!

写一个 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

网页题目:Python 程序:计算字典中项目的和
分享路径:https://chengdu.cdxwcx.cn/article/dhghgih.html