Python类型转换错误

时间:2015-07-27 17:41:15

标签: string python-3.x typeerror

我试图在python中使用str.format()打印给定的结果,但我一直遇到TypeError。这是我当前的一段代码,它给了我错误:

def Restaurant_calorie_average(rest):
    result = []
    for item in rest.menu:
        result.append(item.calories)
    return sum(result)/len(rest.menu)

def Restaurant_str(self: Restaurant) -> str:
return (
    "Name:     " + self.name + "\n" +
    "Cuisine:  " + self.cuisine + "\n" +
    "Phone:    " + self.phone + "\n" +
    "Menu:     " + Menu_str(self.menu) +  "\n"+
    "\t  Average Price: {0:3.2f}.  Average calories {1:}: ".format(Restaurant_price_average(self), str(Restaurant_calorie_average(self))) + "\n\n")

def Collection_str(C: list) -> str:
''' Return a string representing the collection
'''
s = ""
if not C:
    return ''
else:
    for r in C:
        s = s + Restaurant_str(r)
    return s

这是我得到的错误:

    Traceback (most recent call last):
  File "C:\Users\Sage\workspace\hello\restaurantsg.py", line 229, in <module>
    restaurants()
  File "C:\Users\Sage\workspace\hello\restaurantsg.py", line 19, in restaurants
    our_rests = handle_commands(our_rests)
  File "C:\Users\Sage\workspace\hello\restaurantsg.py", line 48, in handle_commands
    print(Collection_str(C))
  File "C:\Users\Sage\workspace\hello\restaurantsg.py", line 176, in Collection_str
    s = s + Restaurant_str(r)
  File "C:\Users\Sage\workspace\hello\restaurantsg.py", line 84, in Restaurant_str
    "\tAverage Price: {0:3.2f}.  Average calories: {1:}".format(Restaurant_price_average(self), Restaurant_calorie_average(self)) + "\n\n")
  File "C:\Users\Sage\workspace\hello\restaurantsg.py", line 113, in Restaurant_calorie_average
    return float(sum(result)/len(rest.menu))
TypeError: unsupported operand type(s) for +: 'int' and 'str'

我不明白的是,我的程序中的另一个函数Restaurant_price_average()具有完全相同的参数并返回类似Restaurant_calorie_average()的浮点数,并且它在当前程序中运行正常我删除了Restaurant_calorie_average()部分。我尝试了类型转换&#39; Restaurant_calorie_average()into string, putting float in format {1:3.1f},但它似乎仍然无效。谁能帮我这个?完整的程序在Rprogram供您参考。

1 个答案:

答案 0 :(得分:1)

错误意味着result列表中的项目的字符串为calories,而不是数字(至少其中一些)。 sum()函数无法正常工作,因为它会在内部将元素添加到0,从而导致出现错误:

In [1]: sum(['42'])
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-1-86653ad6b5d8> in <module>()
----> 1 sum(['42'])

TypeError: unsupported operand type(s) for +: 'int' and 'str'

In [2]: sum([1, 2, '42'])
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-2-c2f90238e02a> in <module>()
----> 1 sum([1, 2, '42'])

TypeError: unsupported operand type(s) for +: 'int' and 'str'

该错误与.format()调用无关,因为正如您在回溯中看到的那样,它发生在Restaurant_calorie_average内。

您应修复代码(未在问题中显示),以便rest.menu项仅包含calories属性中的数字。看看你的完整代码,显然这个部分需要修复:

def Dish_get_info() -> Dish:
    """ Prompt user for fields of Dish; create and return.
    """
    return Dish(
        input("Please enter the Dish's name:  "),
        float(input("Please enter the price of that dish:  ")),
        input("Please enter the calories in the food:  ") # <-- you are not converting
                                                          # to float here
        )

作为旁注,我同意Kevin的评论,如果你用方法而不是函数编写实际的类,你会有更多可读的代码。如果你使用函数,它是一个广泛采用的约定,函数名称以小写字母开头。