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

后端 未结 5 1928
暖寄归人
暖寄归人 2020-12-20 04:56

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 be

5条回答
  •  长情又很酷
    2020-12-20 05:27

    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 '-'
    

提交回复
热议问题