python - 对一些杂乱的数据进行迭代和平均

标签 python regex python-2.7

我正在通过函数传递一些困惑的数据。下面的函数尝试取平均值。有时列表中的项目不是数字,并且会引发错误。

我尝试使用正则表达式来替换非数字字符,但有些东西仍然无法通过。每当出现错误值(由于数据困惑)时,我只想为列表中的该项目记录一个 0。

def mean(vals):
    if len(vals) == 0:
        return 0.0

    for val in vals:
        val = re.sub("[^0-9.]", "", str(val))
    print vals
    vals = [float(val) for val in vals]
    return sum(vals) / len(vals)

我打印 vals 列表只是为了看看我在哪里抛出了错误。最后的 vals 列表是:

['</a>']

鉴于我已经对非数字或句点的所有内容进行了正则表达式处理,这怎么可能?

最佳答案

不要使用 re.sub,而是使用 try/ except...

def mean(vals):
    total = 0.0
    length = 0
    for val in vals:
        try:
            total += float(val)
        except (ValueError, TypeError):
             pass
        length += 1
    return total / length if length else 0.0

关于python - 对一些杂乱的数据进行迭代和平均,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30674790/

相关文章:

Python re.sub 将部分字符串更改为 ascii

python - setup.py sdist flattings 包文件结构,删除中间文件夹

python-2.7 - 使用冷冻瓶构建的静态站点没有链接到 index.html 的 CSS 文件

python - 索引错误 : list index out of range/AttributeError: 'list' object has no attribute 'get_attribute'

regex - 记事本中的正则表达式或

java - 尝试学习正则表达式

python - Selenium for Python : Get text() of node that is shared with another element, 通过 XPath

python - 在某些字符之后分割字符串?

python - 如何在适用于 python 3.8 的 AWS lambda 上安装 Pillow?

python - Telegram Bot "chat not found"