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

如何为Python列表中的空/空白项分配默认值

问题:保留列表中空/空白项的默认值映射

问题背景

我有一个待遍历的列表:

ner_issue_lst = [
    'device no power',
    'speaker not work',
    'charge port not work laptop plug charger',
    '',
    'keyboard not functional',
    '',
    ' ',
    'system not charge'
]

需求是为列表中的空值或仅含空白字符的项分配默认值,但原代码使用字典存储结果时遇到问题:空/空白项的键重复,导致无法保留所有空项,最终结果长度和原列表不一致。

原问题代码

res_final = {}
default_val = ('Empty Item | Null', 5.9999)
for index_val, row_val in enumerate(ner_issue_lst):
    if row_val and row_val.strip():
        print('String is neither empty nor blank')
        embed_query_val = model.encode([row_val])
        distance, faiss_value = index.search(embed_query_val, k)
        res_final[row_val] = [labels_lst[index_val] for index_val in faiss_value[0]][
        0
    ], distance.item()
    else:
        print('String is either None or Empty or contain spaces only')
        res_final[row_val] = default_val # 此处无效:键重复导致空项被覆盖

values_lst = list(res_final.values())
faiss_label_lst = [list(tup) for tup in values_lst]
if len(ner_issue_lst) != len(faiss_label_lst):
    print("Input issue list and Output label list must have the same length")

原代码生成的字典输出示例(空项丢失):

{'device no power': ('Power | Battery | Does Not Work', 0.5679274201393127),
 'speaker not work': ('Sound | Audio Sound | External Speakers Not Working',
  0.6274498105049133),
 'charge port not work laptop plug charger': ('Port | Charge Faulty',
  0.5269668698310852), 'keyboard not functional': ('Keyboard | Functional | Not Detected',
  0.3686383068561554),'system not charge': ('Power | Battery | Does Not Charge',
  0.40705418586730957) }

期望输出

需要保留所有空/空白项,输出列表长度和原列表一致:

faiss_label_lst = [['Power | Battery | Does Not Work', 0.5679274201393127],
 ['Sound | Audio Sound | External Speakers Not Working', 0.6274498105049133],
 ['Port | Charge Faulty', 0.5269668698310852],
 ['Empty Item | Null', 5.9999],
 ['Keyboard | Functional | Not Detected', 0.3686383068561554],
 ['Empty Item | Null', 5.9999],
 ['Empty Item | Null', 5.9999],
 ['Power | Battery | Does Not Charge', 0.40705418586730957]]

已解决的代码(改用列表)

将字典替换为列表存储结果,完美保留所有项:

res_final = []
default_val = ['Empty Item | Null', 5.9999]
for index_val, row_val in enumerate(ner_issue_lst):
    if row_val and row_val.strip():
        print('String is neither empty nor blank')
        embed_query_val = model.encode([row_val])
        distance, faiss_value = index.search(embed_query_val, k)
        res_final.append([[labels_lst[index_val] for index_val in faiss_value[0]][
        0
    ], distance.item()])
    else:
        print('String is either None or Empty or contain spaces only')
        res_final.append(default_val)

优化建议

  1. 简化索引取值:原代码中[labels_lst[index_val] for index_val in faiss_value[0]][0]可以直接写成labels_lst[faiss_value[0][0]],减少冗余计算,代码更简洁。
  2. 避免默认值引用冲突:直接appenddefault_val会让所有空项指向同一个列表对象,若后续需要修改单个空项的值,会影响所有同类项。建议改为每次创建新列表:res_final.append(['Empty Item | Null', 5.9999])或res_final.append(default_val.copy())。
  3. 移除调试打印:若无需调试信息,可删除print语句,提升运行效率。
  4. 简化循环结构:可以去掉enumerate(未用到index_val遍历原列表),同时简化循环逻辑:
default_val = ['Empty Item | Null', 5.9999]
res_final = []
for row_val in ner_issue_lst:
    if row_val and row_val.strip():
        embed_query_val = model.encode([row_val])
        distance, faiss_value = index.search(embed_query_val, k)
        res_final.append([labels_lst[faiss_value[0][0]], distance.item()])
    else:
        res_final.append(default_val.copy())

内容的提问来源于stack exchange,提问作者The Humble Coder

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 18:10:50