-2

I'm trying to get the average of a list that has the following format: [["195", "106", "100", "95"]].

Now sum(list1) does not work (used for sum(list1)/len(list1)(while len(list1) works fine):

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

If the list were like this [195,106,100,95] it would work. The same goes wrong if I use numpy.mean(list1). Is there something I can add so this will work? Or maybe a way for me to quickly convert the list format?

SecondLemon
  • 953
  • 2
  • 9
  • 18

2 Answers2

2

If you have a matrix you need to sum the elements of the nested lists. You also need to convert those to integers:

total = sum(int(i) for sublist in outerlist for i in sublist)
length = sum(len(sublist) for sublist in outerlist)
average = total / length

This assumes you wanted the average of all numbers across all nested lists together, so the length needs to reflect the nested list lengths, not the outer list.

Demo using Python 3:

>>> outerlist = [["195", "106", "100", "95"]]
>>> total = sum(int(i) for sublist in outerlist for i in sublist)
>>> length = sum(len(sublist) for sublist in outerlist)
>>> total / length
124.0
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Sorry I've been a bit too vague. I will give you the exact script I've got now. `>>> list0 = [["180", "108", "190", "120"],["190", "102", "100", "120"],["195", "104", "190", "120"],["205", "109", "100", "120"]] >>> list1 = list(map(lambda x:x[0],list0))` Now I would like the sum of list1 – SecondLemon Mar 01 '15 at 13:32
  • Strange, now it suddenly works. Anyway `sum(map(int, list1))` works fine now. Thanks – SecondLemon Mar 01 '15 at 13:36
-1

this error because the elements are strings if you want to get the average use this code

from __future__ import division #for the exact division
x = ["195", "106", "100", "95"]
x_int = [int(y) for y in x]
print sum(x_int) / len(x_int)