gpt4 book ai didi

python - 使用嵌套循环时索引 i 超出数组范围

转载 作者:行者123 更新时间:2023-12-05 04:20:21 26 4
gpt4 key购买 nike

开始学习编码,我正在用 python 自动化无聊的东西来做幻想项目练习。我尝试将 addedItems 数组的每个项目与字典键进行比较,看看它们是否存在,如果不存在,我会创建一个默认值为 1 的新键。但是它说我有索引超出范围错误,尽管为循环并测试它似乎可以毫无问题地迭代的数组,我错过了什么?

`

def displayInventory(inventory):
print("Inventory: ")
item_total = 0
for k, v in inventory.items():
item_total += v
print(v, k)
print("Total number of items: " + str(item_total))

def addToInventory(inventory, addedItems):
items = []
amount = []
print(addedItems)
for keys, values in inventory.items():
items.append(keys)
amount.append(values)

for i in range(len(addedItems)):
for j in range(len(inventory)):
if addedItems[i] == items[i]:
inventory[items[j]] =+ 1
else:
inventory.setdefault(addedItems[i], 1)

inv = {'gold coin': 42, 'rope': 1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
inv = addToInventory(inv, dragonLoot)
displayInventory(inv)

`这是错误信息

['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']

---------------------------------------------------------------------------

IndexError Traceback (most recent call last)

<ipython-input-54-b83d92c005f4> in <module>
26 inv = {'gold coin': 42, 'rope': 1}
27 dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
---> 28 inv = addToInventory(inv, dragonLoot)
29 displayInventory(inv)

<ipython-input-54-b83d92c005f4> in addToInventory(inventory, addedItems)
19 for i in range(len(addedItems)):
20 for j in range(len(inventory)):
---> 21 if addedItems[i] == items[i]:
22 inventory[items[j]] =+ 1
23 else:

IndexError: list index out of range

我尝试在常规 for 循环中测试索引 i,它毫无问题地遍历了项目,我不确定为什么它说超出范围。

编辑:已解决!非常感谢!!!

最佳答案

def displayInventory(inventory):
item_total = 0
for k, v in inventory.items():
item_total += int(v)
print(v, k)
print("Total number of items: " + str(item_total))

def addToInventory(inventory, addedItems):
items = []
amount = []
print(addedItems)
for keys, values in inventory.items():
items.append(keys)
amount.append(values)
for i in range(len(inventory)):
for j in range(len(addedItems)):
if addedItems[j] == items[i]:
inventory[items[i]] += 1
else:
inventory.setdefault(addedItems[i], 1)
return inventory

inv = {'gold coin': 42, 'rope': 1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
inv = addToInventory(inv, dragonLoot)
displayInventory(inv)

关于python - 使用嵌套循环时索引 i 超出数组范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74516186/

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