Skip to main content
 首页 » 编程设计

python之数字列表的平均值,在 Python 列表中存储为字符串

2025年05月04日23qq号

我想用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 '-' 

附言我正在使用 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 '-'