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

如何在Python列表的空位置填充0?

Python列表空白位置填充'0'的实现方案

你给出的场景是需要把列表中内容为单个空格的元素替换为字符串类型的'0',可以用以下几种方式实现:

  • 方法1:列表推导式(生成新列表,不修改原列表,一行代码即可完成)
    代码示例:
    list_1 = ['2','4',' ','3',' ','1',' ']
    new_list = [item if item != ' ' else '0' for item in list_1]
    print(new_list)
    
    运行输出:['2', '4', '0', '3', '0', '1', '0']
  • 方法2:兼容多空格、空白字符的替换方案
    如果你的“空位置”可能存在多个空格、制表符等纯空白内容,可使用strip()方法判断更稳妥:
    new_list = [item if item.strip() else '0' for item in list_1]
    
  • 方法3:直接修改原列表
    如果不需要保留原列表内容,可以直接遍历索引修改:
    list_1 = ['2','4',' ','3',' ','1',' ']
    for idx in range(len(list_1)):
        if list_1[idx] == ' ':
            list_1[idx] = '0'
    print(list_1)
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 17:09:01