You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Robot Framework中如何将List of lists中的None替换为0.00

嘿,这个需求在处理数据库返回数据时太常见了!我给你分享几个实用的Python实现方法,根据你的数据复杂度选就行:

方法一:嵌套列表推导式(最推荐)

这是最简洁也最Pythonic的写法,直接双层遍历,遇到None就替换成0.00,否则保留原元素,可读性拉满:

# 假设你的数据库返回数据长这样
db_records = [[1, None, 3.14], [None, 5, None], [7.77, 8, 9]]

# 执行替换
processed_records = [[0.00 if item is None else item for item in sublist] for sublist in db_records]

# 输出结果:[[1, 0.0, 3.14], [0.0, 5, 0.0], [7.77, 8, 9]]

这里要注意用item is None而不是item == None,因为is是判断对象身份,比==更准确,避免一些特殊情况的误判。

方法二:用map函数(函数式风格)

如果你偏爱函数式编程的写法,可以用map结合匿名函数来实现,逻辑和列表推导式一致:

processed_records = list(map(lambda sublist: list(map(lambda x: 0.00 if x is None else x, sublist)), db_records))

外层map负责遍历每个子列表,内层map处理子列表里的每个元素,最后转成列表即可。不过可读性稍逊于列表推导式,看个人编程习惯选择。

方法三:递归处理深层嵌套(可选)

如果你的数据存在多层嵌套(比如列表里还有子列表,子列表里还有子列表),上面的方法就搞不定了,这时候写个递归函数更靠谱:

def replace_none_with_zero(lst):
    processed_list = []
    for item in lst:
        # 如果当前元素是列表,递归处理
        if isinstance(item, list):
            processed_list.append(replace_none_with_zero(item))
        else:
            # 不是列表就判断是否为None,替换成0.00
            processed_list.append(0.00 if item is None else item)
    return processed_list

# 调用示例
processed_records = replace_none_with_zero(db_records)

这个函数会逐层遍历所有嵌套的列表,把所有遇到的None都替换成0.00,不管嵌套多少层,适合结构复杂的数据。

内容的提问来源于stack exchange,提问作者bbk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 08:12:18