gpt4 book ai didi

Python 3 代码按预期工作,但我不明白为什么

转载 作者:行者123 更新时间:2023-12-01 03:06:11 24 4
gpt4 key购买 nike

代码:

inv = {'arrow': 12, 'gold coin': 42, 'rope': 1, 'torch': 6, 'dagger': 1}

def show_inv():
print('inventory:')
item_total = 0
for k, v in inv.items():
print(str(v)+ ' ' + (k))
item_total = item_total + v
print('total number of items: ' + str(item_total))

show_inv()

结果(如预期):

inventory:

12 arrow

42 gold coin

1 rope

6 torch

1 dagger

total number of items: 62

但是怎么办

item_total = item_total + v

给我正确的总值(value)?

编辑:为什么 print(str(v)) 总是单独给我“dagger”键的值?

最佳答案

这里重要的几行是:

for k, v in inv.items():
# do stuff

当您使用for时-循环字典的 items迭代器,它将循环 keyvalue该词典的 s 。由于您有一个从名称到值的字典,values ( v ) 将是每个项目的值。将它们全部相加即可得到正确的总值(value)。

线路

item_total = item_total + v 

对库存中的每个项目运行一次,因为它位于 for 范围内。 -在库存上运行的循环。

阅读 Iterators in Python可能会帮助您理解为什么这是有效的。

关于Python 3 代码按预期工作,但我不明白为什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43399670/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com