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

如何将字典列表中options内的指定答案替换为'None of the above'

替换字典列表中选项的指定值

问题背景

给定如下字典列表:

input = [
    {'options': ['IndoAryan', 'Vedic Brahmanism', 'the 3rd century', '4th'], 
     'answer': '4th', 
     'question': 'What religions were synthesised with the preexisting cultures of the subcontinent?', 
     'context': 'During this period aspects of Indian civilisation administration culture and religion Hinduism and Buddhism spread to much of Asia while kingdoms in southern India had maritime business links with the Middle East and the Mediterranean.', 
     'rank': 45},
    {'options': ['Classical', 'the Maurya Empire', 'Wootz', 'BCE'], 
     'answer': 'BCE', 
     'question': 'What Empire ruled the Indian subcontinent?', 
     'context': 'During this period aspects of Indian civilisation administration culture and religion Hinduism and Buddhism spread to much of Asia while kingdoms in southern India had maritime business links with the Middle East and the Mediterranean.', 
     'rank': 9}
]

需要实现的功能:遍历每个字典,将options列表中与当前字典answer字段值相同的元素,替换为'None of the above'。

解决方案

可以通过遍历列表中的每个字典,对options列表进行元素替换操作:

# 遍历每个字典
for item in input:
    # 获取当前字典的answer值
    ans = item['answer']
    # 替换options中对应的元素
    item['options'] = ['None of the above' if opt == ans else opt for opt in item['options']]

# 查看结果
print(input)

执行结果

运行上述代码后,得到的输出如下:

[
    {'options': ['IndoAryan', 'Vedic Brahmanism', 'the 3rd century', 'None of the above'], 
     'answer': '4th', 
     'question': 'What religions were synthesised with the preexisting cultures of the subcontinent?', 
     'context': 'During this period aspects of Indian civilisation administration culture and religion Hinduism and Buddhism spread to much of Asia while kingdoms in southern India had maritime business links with the Middle East and the Mediterranean.', 
     'rank': 45},
    {'options': ['Classical', 'the Maurya Empire', 'Wootz', 'None of the above'], 
     'answer': 'BCE', 
     'question': 'What Empire ruled the Indian subcontinent?', 
     'context': 'During this period aspects of Indian civilisation administration culture and religion Hinduism and Buddhism spread to much of Asia while kingdoms in southern India had maritime business links with the Middle East and the Mediterranean.', 
     'rank': 9}
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 03:24:23