use*_*ser 1 python list-comprehension
我想计算python中几个列表的平均值。这些列表包含数字作为字符串。空字符串不是零,它意味着缺少值。
我能想到的最好的就是这个。有没有更优雅,简洁和有效的方式来写这个?
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 '-'
PS 我正在使用 Python 2.7.x 但欢迎使用 Python 3.x 的食谱
num = ['1', '2', '', '6']
L = [int(n) for n in num if n]
ave = sum(L)/float(len(L)) if L else '-'
或者
num = ['1', '2', '', '6']
L = [float(n) for n in num if n]
avg = sum(L)/len(L) if L else '-'