Search code examples
pythonlist-comprehension

Average of a list of numbers, stored as strings in a Python list


I want to calculate the average value of several lists in python. These lists contain numbers as strings. Empty string isn't zero, it means a missing value.

The best I could come up with is this. Is there a more elegant, succinct & efficient way of writing this?

num    = ['1', '2', '', '6']
total  = sum([int(n) if n else 0 for n in num])
length = sum([1 if n else 0 for n in num])
ave    = float(total)/length if length > 0 else '-'

P.S. I'm using Python 2.7.x but recipes for Python 3.x are welcome


Solution

  • num = ['1', '2', '', '6']
    L = [int(n) for n in num if n]
    ave = sum(L)/float(len(L)) if L else '-'
    

    or

    num = ['1', '2', '', '6']
    L = [float(n) for n in num if n]
    avg = sum(L)/len(L) if L else '-'