简体   繁体   中英

typeerror unsupported operand type(s) for / 'str' and 'int'

I'm trying to find the average score from a list if three numbers, as shown below:

a = (lines.split(":")[1].split(",")[-3:])
Print (a)
Averagescore = sum(a)/len(a)
Print (averagescore)

Then it says: typeerror unsupported operand type(s) for / 'str' and 'int'

I suspect that the error message as you describe may not be accurate for this code, but nonetheless, the issue is that you are trying to treat a list of strings as a list of ints. for example

>>> s = "1 16 32" # string
>>> s.split() # this returns a list of strings
['1', '16', '32']
>>> s.split()[0] + 1 # you can't add an int to a string
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't convert 'int' object to str implicitly

If you want to treat them as ints (or floats) then you will need to add the conversion as in

a = [int(n) for n in s.split()]
a = [float(n) for n in s.split()] # alternatively

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM