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

协助修复从列表生成特定字典的Python函数(遇EOF错误)

语法错误排查与修复

原代码存在多处语法问题,直接引发运行报错:

  • word.index() 调用错误:index() 是列表的方法,需通过 words.index(word) 调用,但该方法在处理重复元素时仅返回首次出现的索引,会导致后续逻辑错误。
  • words.len() 不符合Python语法:获取列表长度需用 len(words)。
  • words(words.index(word)+1) 语法错误:取列表元素要用方括号 [],正确写法为 words[words.index(word)+1]。
  • 遍历方式不合理:直接遍历元素值无法处理重复键,重复元素的 index() 会返回首次出现的位置,导致后续元素关联错误。

逻辑错误修正

原逻辑的核心问题是依赖元素值取索引的方式,无法处理重复出现的键。比如示例中"one"出现两次,第一次对应后续元素"two",第二次对应"three",用words.index("one")只能拿到第一个索引,无法关联第二个"one"对应的"three"。

正确思路是通过索引遍历,仅遍历到倒数第二个元素(最后一个元素无后续单词),每次取当前索引的元素作为键,下一个索引的元素作为值追加到列表中。

修复后的代码

def build_predictions(words: list) -> dict:
    dictionary = {}
    # 遍历范围:从第一个元素到倒数第二个元素
    for i in range(len(words) - 1):
        current_word = words[i]
        next_word = words[i + 1]
        # 键不存在则初始化空列表
        if current_word not in dictionary:
            dictionary[current_word] = []
        # 追加后续单词
        dictionary[current_word].append(next_word)
    return dictionary

示例验证

运行示例输入:

print(build_predictions(["ONE", "two", "one", "three"]))

输出结果:

{"ONE": ["two"], "two": ["one"], "one": ["three"]}

若需要忽略大小写匹配(和你给出的示例结果一致),可修改代码统一转小写:

def build_predictions(words: list) -> dict:
    dictionary = {}
    for i in range(len(words) - 1):
        current_word = words[i].lower()
        next_word = words[i + 1].lower()
        if current_word not in dictionary:
            dictionary[current_word] = []
        dictionary[current_word].append(next_word)
    return dictionary

此时输出:

{"one": ["two", "three"], "two": ["one"]}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 02:40:18