How do you find the average of a list with quoted numbers, in python?

I have two types of lists. The first one without quotes, which works and prints the average penalty:

l = [15,18,20]
print l
print "Average: ", sum(l)/len(l)

      

Prints:

[15,18,20]
Average: 17

      

In the second list there are numbers with quotation marks, that return an error :

x = ["15","18","20"]
print x
print "Average: ", sum(x)/len(x)

      

Mistake:

TypeError: unsupported operand type(s) for +: 'int' and 'str'

      

How do you compute a list with quoted value numbers?

+3


source to share


3 answers


The quotes mean that you have a list of strings:

>>> x = ["15","18","20"]
>>> type(x[0])
<type 'str'>
>>>

      

sum

only works with lists of numbers (integers like 1

or floats like 1.0

).

To fix your problem, you first need to convert the list of strings to a list of integers. You can use the built-in map

function
for this:

x = ["15","18","20"]
x = map(int, x)

      



Or, you can use a list comprehension (which many Python programmers prefer):

x = ["15","18","20"]
x = [int(i) for i in x]

      

Below is a demo:

>>> x = ["15","18","20"]
>>> x = map(int, x)
>>> x
[15, 18, 20]
>>> type(x[0])
<type 'int'>
>>> sum(x) / len(x)
17
>>>

      

+9


source


you need to convert them to int

:

x = ["15","18","20"]
print sum(map(int,x))/len(x)

      



here will map

map each element x to an integer type

+3


source


print "Average of {list} is: {avg}".format(
    list=l,
    avg=sum(int(x) for x in l) / len(l),
)

      

+2


source







All Articles