数字列表的平均值,以字符串形式存储在Python列表中 [英] Average of a list of numbers, stored as strings in a Python list
本文介绍了数字列表的平均值,以字符串形式存储在Python列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想计算python中多个列表的平均值.这些列表包含数字作为字符串.空字符串不为零,表示缺少值.
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.我使用的是Python 2.7.x,但欢迎使用Python 3.x的食谱
P.S. I'm using Python 2.7.x but recipes for Python 3.x are welcome
推荐答案
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 '-'
这篇关于数字列表的平均值,以字符串形式存储在Python列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文