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

如何用1-5的数值范围替换字典列表中空的Dependants字段值

替换空Dependants字段为1-5范围内的数值

可以通过Python的random模块生成指定范围的随机数,直接修改目标字典的字段值即可,以下是两种实现方式:

方式一:直接遍历原列表处理

不需要单独提取异常条目,直接遍历整个Customer_Details列表,检查并替换空字段:

import random

for customer in Customer_Details:
    if customer['Dependants'] == '':
        # 生成1-5的整数,转为字符串保持与原有数据类型一致
        customer['Dependants'] = str(random.randint(1, 5))

方式二:利用已提取的异常列表处理

既然已经通过列表推导式得到了Customers_with_dependant_issues,直接遍历这个列表修改即可(字典是可变对象,修改会同步到原列表):

import random

for customer in Customers_with_dependant_issues:
    customer['Dependants'] = str(random.randint(1, 5))

补充说明

  • 如果不需要随机值,想统一替换为某个固定数值(比如1),直接把str(random.randint(1, 5))改成'1'即可;
  • 若原数据允许Dependants为整数类型,也可以去掉str()转换,直接赋值整数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 14:08:21