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

后端 未结 5 1734
一生所求
一生所求 2020-12-20 04:36

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:17

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

提交回复
热议问题