-2

I have a list in python and I want to get the average of all items. I tried different functions and even I wrote a small function for that but could not do that. even when I tried to convert the items to a int or float it gave these errors:

TypeError: float() argument must be a string or a number 
TypeError: int() argument must be a string or a number, not 'list'

here is a small example of my list in python.

['0,0459016', '0,0426647', '0,0324087', '0,0222222', '0,0263356']

do you guys know how to get the average of items in such list/ thanks

martineau
  • 119,623
  • 25
  • 170
  • 301
user3925736
  • 99
  • 1
  • 1
  • 13

3 Answers3

1

Assuming that '0,0459016' means '0.0459016':

In [6]: l = ['0,0459016', '0,0426647', '0,0324087', '0,0222222', '0,0263356']

In [7]: reduce(lambda x, y: x + y, map(lambda z: float(z.replace(',', '.')), l)) / len(l)
Out[7]: 0.033906559999999995
Nehal J Wani
  • 16,071
  • 3
  • 64
  • 89
0

Please refer to How can I convert a string with dot and comma into a float number in Python

sum([float(v.replace(",", ".")) for v in a]) / len(a)

where a is your original list.

Community
  • 1
  • 1
chriss
  • 4,349
  • 8
  • 29
  • 36
  • 1
    If a question can be answered by an existing post, please mark the question as a duplicate instead of making an identical answer. Additionally, this is the wrong method - you really should be using the `locale` module. – MattDMo Aug 20 '16 at 11:53
0

Try this,

In [1]: sum(map(float,[i.replace(',','.') for i in lst]))/len(lst)
Out[1]: 0.033906559999999995

Actulluy there is 2 problem in your list. The elements are string and instead of . it having ,. So we have to convert to normal form. like this.

In [11]: map(float,[i.replace(',','.') for i in lst])
Out[11]: [0.0459016, 0.0426647, 0.0324087, 0.0222222, 0.0263356]

Then perform the average.

Rahul K P
  • 15,740
  • 4
  • 35
  • 52