Python3.x 将“ ”更改为整数/浮点数。从列表中计算平均值

Python3.x Changing ' ' into an integer/ float. Calculating average from a list

我正在尝试将列表中的“”更改为整数或浮点数。假设我有一个列表

    allprices = ['', '', '', 1.2, 3.2, 1.8, '', '', '', '', '', '']

我想将空字符串更改为浮点数或整数我不确定那部分但很确定它们最后必须是浮点数因为我要计算平均值。现在,我有另一个名为

的列表
    averages = []

列表"allprices"基本上是由子列表组成的元素列表列表。它有 6 个级别。我尝试用 0 替换 '' 并且成功了。但是无法想出如何使用命令进行更改的方法。我在此处或其他论坛中找到了一些示例和命令,但对我不起作用。我尝试的第一件事是

    var = ''
    var1= 0
    var = var1

但这给出了一些错误。我也试过直接把它做成一个浮点数,但也没用。请帮助或指导我找到另一个标题,以便我弄清楚。顺便说一句,我是编程新手,所以我尝试做的事情可能看起来不是解决这个问题的便捷方法,但只要它对我有用,我就很高兴。

计算平均值的时候忽略它们:

>>> allprices = ['', '', '', 1.2, 3.2, 1.8, '', '', '', '', '', '']
>>> sum(x for x in allprices if x)/len(allprices)
0.5166666666666667

注意 - 这依赖于 '' 的 'non truthiness'。如果您的列表元素原本是 'truthy'(例如 ' ')但应该被过滤,请适当调整您的 if 子句:

>>> allprices = ['', '', '', 1.2, 3.2, 1.8, '', '', '', '', '', ' ']
>>> sum(x for x in allprices if isinstance(x, (float, int)))/len(allprices)
0.5166666666666667

如果您可能有 class 个不是 intfloat 的数字,请使用抽象基数 class Numbers 进行过滤:

>>> import numbers
>>> sum(x for x in allprices if isinstance(x, numbers.Number))/len(allprices)
0.5166666666666667

如果你想用 0 实际替换 '' 使用列表理解:

>>> [e if e else 0 for e in allprices]
[0, 0, 0, 1.2, 3.2, 1.8, 0, 0, 0, 0, 0, 0]

或者,

>>> [e if isinstance(e, (float, int)) else 0 for e in allprices]
[0, 0, 0, 1.2, 3.2, 1.8, 0, 0, 0, 0, 0, 0]

另一个解决方案filter

>>> sum(filter(None, allprices))/len(allprices)
0.5166666666666667

filter(None, ...) 将剔除所有虚假的元素,例如空字符串或值 0。后者很好,因为它不会在计算总和时产生影响。