【问题标题】:TypeError: unsupported operand type(s) for +: 'int' and 'str' when using str(sum(list))类型错误:+ 不支持的操作数类型:使用 str(sum(list)) 时的“int”和“str”
【发布时间】:2020-01-29 10:22:33
【问题描述】:

我正在阅读 Python 教程,但不知道为什么我的代码不起作用。我知道我需要告诉 Python 手动打印一个整数,但我已经输入了str(sum(ages))。谁能告诉我为什么会这样?

ages = ['24','34','51','36','57','21','28']

print('The oldest in the group is ' + str(max(ages)) + '.')

print('The youngest in the group is ' + str(min(ages)) + '.')

print('The combined age of all in the list is ' + str(sum(ages)) + '.')

错误:

File "list2.py", line 4, in <module>
    print('The combined age of all in the list is ' + str(sum(ages)) + '.')

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

【问题讨论】:

    标签: python python-3.x string list sum


    【解决方案1】:

    问题是您不能在字符串列表上使用sum。为此,您可以先使用生成器表达式将每个元素转换为整数:

    print('The combined age of all in the list is ' + str(sum(int(x) for x in ages)) + '.')
    

    这给了我们:

    The combined age of all in the list is 251.
    

    【讨论】:

    • 好的,谢谢。你知道为什么这段代码有效吗? wallets = [20,15,25,41] print('总金额为:' + str(sum(wallets)))
    • 这就是我感到困惑的原因。为什么该代码有效但使用相同的 str(sum(ages)) 不适用于问题中的代码?
    • @MauricePhilipps 因为ages 中的元素是字符串,wallets 中的元素是整数。注意ages 中每个元素的引号。
    猜你喜欢
    • 2014-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-27
    • 2021-06-18
    • 2013-10-12
    • 2018-02-05
    相关资源
    最近更新 更多