问题
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)) + '.')
Error:
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'
回答1:
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)) + '.')
Which gives us:
The combined age of all in the list is 251.
来源:https://stackoverflow.com/questions/59965010/typeerror-unsupported-operand-types-for-int-and-str-when-using-strsum