【问题标题】:Including an if statement for a merged dictionary causes 'TypeError: 'int' object is not callable包含合并字典的 if 语句会导致 \'TypeError: \'int\' object is not callable
【发布时间】:2022-10-06 02:51:36
【问题描述】:

第一次在这里发布海报和 Python 新手。

为了掌握 Python 的基础知识,我从阅读 Al Sweigart 的 Automate The Boring Stuff 开始,我认为我会尝试参与其中的一个迷你项目,那就是“Fantasy Inventory” “ 项目。我设法弄清楚它是如何通过一些试验和错误(以及大量谷歌搜索)工作的,但这是最终代码:

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

def displayInventory(inventory):
    total_items = 0
    for item, quantity in inventory.items():
        print(str(quantity) + \' \' + item)
        total_items += quantity
    print(\"Total number of items: \" + str(total_items))

displayInventory(stuff)

我决定尝试包含一个“珍贵矿物质”字典,这样它就可以为文本添加一点额外的味道,包括一个 if 和 elif 语句,如果preciousMineral 总数为 0 或大于 0。代码现在看起来像这样:

stuff = {\'arrows\': 41, \'sword\': 1, \'dagger\': 2, \'torch\': 1}
preciousMinerals = {\'rubies\': 0, \'emeralds\': 0, \'sapphires\': 0}
stuffAndMinerals = stuff|preciousMinerals

def displayInventory(inventory):
    total_items = 0
    for item, quantity in inventory.items():
        print(str(quantity) + \' \' + item)
        total_items += quantity
    print(\'You have a total of \' + str(total_items) + \' items in your bag.\')
    if str(quantity(preciousMinerals)) == 0:
        print(\'You have no precious minerals.\')
    elif str(quantity(preciousMinerals)) > 0:
        print(\'You have some precious minerals in your bag.\')
        print(\'You have: \' + str(quantity(preciousMinerals[0]) + \', \' +
                             str(quantity(preciousMinerals[1]) + \', \' +
                             str(quantity(preciousMinerals[2]) + \'.\'))))
displayInventory(stuffAndMinerals)

在添加珍贵矿物之前,代码运行流畅,没有错误。但是,我现在在线收到一个 \'TypeError: \'int\' object is not callable\' 错误:

if str(quantity(preciousMinerals)) == 0:

任何帮助将不胜感激!非常感谢。

  • quantity 是一个整数变量,而不是一个函数。您需要if sum(preciousMinerals.values()):,并从您的最终打印语句中删除quantity((3 次)。 quantity 不参与其中。

标签: python list dictionary typeerror callable


【解决方案1】:

您正在尝试调用quantity,这是一个带有preciousMinerals 的int:

if str(quantity(preciousMinerals)) == 0: 我建议您跟踪您在代码中使用的类型。每种类型都有自己的能力,有些不能做,有些可以。

这对你来说很好:

stuff = {'arrows': 41, 'sword': 1, 'dagger': 2, 'torch': 1}
precious_minerals = {'rubies': 1, 'emeralds': 0, 'sapphires': 0}
stuff_and_minerals = stuff|precious_minerals

def display_inventory(inventory):
    total_items = 0
    for item, quantity in inventory.items():
        print(f"You have {quantity} {item}")
        total_items += quantity

    print(f"You have a total of {total_items} items in your bag.")

    if sum(precious_minerals.values()) == 0:
        print('You have no precious minerals.')
    elif sum(precious_minerals.values()) > 0:
        print('You have some precious minerals in your bag.')
        for item, quantity in precious_minerals.items():
            print(f"You have {quantity} {item}")

display_inventory(stuff_and_minerals)

【讨论】:

【解决方案2】:

这是似乎有效的代码,我希望这是您所要求的:

#!/usr/bin/env python3

stuff = {'arrows': 41, 'sword': 1, 'dagger': 2, 'torch': 1}
preciousMinerals = {'rubies': 0, 'emeralds': 2, 'sapphires': 1}
stuffAndMinerals = stuff|preciousMinerals

def displayInventory(inventory):
    total_items = 0
    for item, quantity in inventory.items():
        print(str(quantity) + ' ' + item)
        total_items += quantity
    print('You have a total of ' + str(total_items) + ' items in your bag.')

    if sum(preciousMinerals.values()) == 0: # get the content of preciousMinerals, will look like dict_values[0, 2, 1] in this case
                                            # won't tell anything about dict_valuesm see more here (recommended): https://stackoverflow.com/questions/33674033/python-how-to-convert-a-dictionary-into-a-subscriptable-array
        print('You have no precious minerals.')
    elif sum(preciousMinerals.values()) > 0:
        print('You have some precious minerals in your bag.')
        nrOfAllPreciousMinerals = list(preciousMinerals.values()) # remember: list(dict_values[0, 2, 1]) => removes the dict_values, see the link above

        # count the number of minerals greater than 0
        nrOfYourPreciousMinerals = 0
        for mineral in nrOfAllPreciousMinerals:
            if mineral > 0:
                nrOfYourPreciousMinerals += 1


        print("You have: ", end="") # end="" removes the newline
        i = 0
        for item in preciousMinerals:
            if preciousMinerals[item] != 0:
                print(item, end="")
                if nrOfYourPreciousMinerals > i+1: # +1 because enumerate() starts counting at zero
                    print(",", end=" ") # end=SomeString defines what shall be printed if the whole print() is done - in this case it's a space
                else:
                    print(".")

                i += 1





displayInventory(stuffAndMinerals)

cmets 可能会澄清我的所作所为。我不知道你想做什么以及为什么这样做。

如果您有任何问题,请发表评论。

【讨论】:

    【解决方案3】:

    首先,我认为您将传递给函数的 inventory 变量与在函数外部声明的变量 preciousMinerals 混合在一起。

    此外,您正在尝试在其范围之外使用 quantity(这是 for 循环),并像调用它一样调用它,如果它是一个函数,而它是一个数字。

    让我尝试通过参考实现来帮助您,希望事情会变得更加清晰:

    # keep a list of known items and their categories
    catalog = {
      'boring items': {'arrows', 'sword', 'dagger', 'torch'},
      'precious minerals': {'rubies', 'emeralds', 'sapphires'}
    }
    
    def displayInventory(inventory):
      if not any(inventory.values()):
        print('You do not have anything, get out!')
        return
      remaining = set(inventory.keys())
      for category, cat_items in catalog.items():
        matching = {itm: inventory[itm] for itm in (remaining & cat_items)}
        if not any(matching.values()):
          print(f'You have no {category}.')
          continue
        print(f'These are all the {category} you have:')
        print(*(f'  {k} {v}' for k, v in matching.items()), sep=',\n')
        print(f'  You have a total of {sum(matching.values())} {category} in your bag.')
        remaining.difference_update(cat_items)
      if any(remaining):
        matching = {itm: inventory[itm] for itm in remaining}
        print('You have some unknown items:')
        print(*(f'  {k} {v}' for k, v in matching.items()), sep=',\n')
    
    
    displayInventory({'arrows': 41, 'sword': 1, 'dagger': 2, 'torch': 1})
    displayInventory({'rubies': 0, 'emeralds': 0, 'sapphires': 0})
    displayInventory({'rubies': 4, 'torch': 7, 'dagger': 0, 'cheese': 4})
    

    【讨论】:

      猜你喜欢
      • 2015-01-05
      • 2021-10-22
      • 1970-01-01
      • 1970-01-01
      • 2018-07-23
      • 2017-04-06
      • 2013-03-30
      • 2022-12-26
      • 1970-01-01
      相关资源
      最近更新 更多