当从数组向字典中添加项时,我得到一个错误??PYTHON 3.x版

2024-06-16 11:25:51 发布

您现在位置:Python中文网/ 问答频道 /正文

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



def displayInventory(inventory):
    print("Inventory:")
    item_total = 0
    for k, v in inventory.items():

        print(str(v) + " " + k)
        item_total += v

    print("Total number of items: " + str(item_total) + '\n')

displayInventory(stuff)

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

inv = {'gold coin': 42, 'rope': 1}

def addToInventory(ram, addedItems):

  for itemindex in addedItems:
    if itemindex not in ram:
      ram[itemindex] = 0

    ram[itemindex] = ram[itemindex] + 1

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

inv = addToInventory(inv, dragonLoot)

displayInventory(inv)

当我这样做的时候,它会返回这样一个错误。。。你知道吗

Inventory:
1 rope
6 torch
1 dagger
12 arrow
Total number of items: 62

Inventory:
Traceback (most recent call last):
  File "python", line 33, in <module>
  File "python", line 8, in displayInventory
AttributeError: 'NoneType' object has no attribute 'items'

考虑到将inv更改为'abc'或除inv以外的任何内容时,错误会消失,代码运行平稳,这是没有意义的。你知道吗


Tags: initemsitemramtotalinventorycoinprint
1条回答
网友
1楼 · 发布于 2024-06-16 11:25:51

您正在将inv传递给displayInventory,但是由于addToInventory不返回任何内容,invNone,因此没有属性items()。你知道吗

inv=addToInventory(inv, dragonLoot) #inv=None since addToInventory returns nothing
displayInventory(inv) #passing it None
    for k, v in inventory.items(): #None.items() is obviously invalid, creates error

相关问题 更多 >