Python 模式匹配的安全索引

Safe indexing with pattern matching in Python

我有一个巨大的单词列表 corpus 和一个特定的单词 w。我知道 w 在语料库中每次出现的索引。我想查看 w 每次出现的 n 大小 window 并创建出现在 window 中的其他单词的字典。字典是从 intlist[str] 的映射,其中关键是距离我的目标词有多少位置,向左(负)或向右(正),以及值是该位置的单词列表。

例如,如果我有语料库:["I", "made", "burgers", "Jack", "made", "sushi"];我的话是 "made" 并且我正在看 window 大小 1,那么我最终想要 return {-1: ["I", "Jack"], 1: ["burgers", "sushi"]}.

可能会出现两个问题。我的 window 可能会越界(如果我在上面的示例中查看大小为 2 的 window)并且我可能会在 window 中多次遇到同一个词,这是情况我想忽略。我已经编写了以下似乎有效的代码,但我想使这个 cleaner.

def find_neighbor(word: str, corpus: list[str], n: int = 1) -> dict[int, list[str]]:
    mapping = {k: [] for k in list(range(-n,n+1)) if k != 0}
    idxs = [k for k, v in enumerate(corpus) if v == word]
    for idx in idxs:
        for i in [x for x in range(-n,n+1) if x != 0]:
            try:
                item = corpus[idx+i]
                if item != word:
                    mapping[i].append(corpus[item])
            except IndexError:
                continue
    return mapping

有没有办法合并 选项 和模式匹配,这样我就可以删除 try 块并拥有类似这样的东西...

match corpus[idx+i] 
  case None: continue; # If it doesn't exist (out of bounds), continue / i can also break
  case word: continue; # If it is the word itself, continue
  case _: mapping[i].append(corpus[item]) # Otherwise, add it to the dictionary

引入辅助函数returns corpus[i] if i is a legal index and None otherwise:

corpus = ["foo", "bar", "baz"]

def get(i):
    return corpus[i] if i<len(corpus) else None
        
print([get(0), get(1), get(2), get(3)])

以上结果为:

['foo', 'bar', 'baz', None]

现在你可以写:

match get(idx+i)
  case None: something
  case word: something
  case _:    something