首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >TypeError:使用str(sum(list))时+:'int‘和'str’的操作数类型不受支持

TypeError:使用str(sum(list))时+:'int‘和'str’的操作数类型不受支持
EN

Stack Overflow用户
提问于 2020-01-29 18:22:34
回答 1查看 360关注 0票数 0

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

代码语言:javascript
运行
复制
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)) + '.')

错误:

代码语言:javascript
运行
复制
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'
EN

回答 1

Stack Overflow用户

发布于 2020-01-29 18:27:52

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

代码语言:javascript
运行
复制
print('The combined age of all in the list is ' + str(sum(int(x) for x in ages)) + '.')

这就给我们提供了:

代码语言:javascript
运行
复制
The combined age of all in the list is 251.
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59965010

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档