TypeError:+不支持的操作数类型:使用str(sum(list))时为'int'和'str' [英] TypeError: unsupported operand type(s) for +: 'int' and 'str' when using str(sum(list))
本文介绍了TypeError:+不支持的操作数类型:使用str(sum(list))时为'int'和'str'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在阅读Python教程,不知道为什么我的代码无法正常工作.我知道我需要告诉Python手动打印整数,但是我已经放了 str(sum(ages))
.谁能告诉我为什么会这样?
I'm going through the Python tutorial and have no idea why my code isn't working. I know I need to tell Python to print an integer manually but I have already put str(sum(ages))
. Can anyone tell me why this is happening?
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'
推荐答案
问题是您不能在字符串列表上使用 sum
.为此,您可以使用生成器表达式先将每个元素转换为整数:
The issue is that you can't use sum
on a list of strings. In order to do this, you can use a generator expression to convert each element to an integer first:
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.
这篇关于TypeError:+不支持的操作数类型:使用str(sum(list))时为'int'和'str'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文