我正在看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'发布于 2020-01-29 18:27:52
问题是你不能在字符串列表上使用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.https://stackoverflow.com/questions/59965010
复制相似问题