【问题标题】:index out of range error while working with lists in python在 python 中使用列表时出现索引超出范围错误
【发布时间】:2014-02-26 20:32:26
【问题描述】:

我正在为我的项目目的编写一个 python 代码,在该代码中我想实现窗口机制(目标单词的周围单词),并且我已经为它编写了以下部分,下面给出了一个示例列表。当目标词没有被两边至少两个词包围时,我得到“索引超出范围”。

Window = list()
text = ['dog','bark','tree']
polysemy = ['dog','bark','tree']

def window_elements(win,ind,txt):
    win.append(txt[index + 1])
    win.append(txt[index + 2])
    win.append(txt[index - 1])
    win.append(txt[index - 2])
    return win
for w in polysemy:
    window = list()
    index = text.index(w)
    window = window_elements(window,index,text)

假设这里 for 循环的第一次执行目标词是'dog',所以从函数 window_element 我想要一个来自'dog'右侧的单词 2 和来自'dog'左侧的 2 个单词的列表。但是这里 dog 的左侧没有单词,因此该列表将不包含任何单词,并且仅从右侧取两个单词并正确执行。
我想要这种机制,但无法以上述方式做到这一点。任何人都可以建议我满足我的要求的可选机制吗?

【问题讨论】:

  • 你到底想要什么?请举个例子
  • 请看我解释的变化
  • 为什么你将ind 参数传递给你的函数,然后在函数内部使用全局index?

标签: python python-2.7


【解决方案1】:

您可以为此使用切片:

def window(lst, index):
    return lst[max(0,index-2):index+3]

例如:

>>> for i in range(10):
        print(i, window(list(range(10)), i))


0 [0, 1, 2]
1 [0, 1, 2, 3]
2 [0, 1, 2, 3, 4]
3 [1, 2, 3, 4, 5]
4 [2, 3, 4, 5, 6]
5 [3, 4, 5, 6, 7]
6 [4, 5, 6, 7, 8]
7 [5, 6, 7, 8, 9]
8 [6, 7, 8, 9]
9 [7, 8, 9]

如果上索引超出范围,切片将“优雅地失败”,并尽可能多地返回。

【讨论】:

    【解决方案2】:

    您可以尝试以下功能。它会正常工作。

    def window_elements(win,ind,txt):
    if(len(txt) == 1):
        return
    elif(ind == 0 and len(txt) == 2):
        win.append(txt[1])
    elif(ind == 1 and len(txt) == 2):
        win.append(txt[0])
    elif(ind == 0):
        win.append(txt[index + 1])
        win.append(txt[index + 2])
    elif(ind == (len(txt) - 1)):
        win.append(txt[index - 1])
        win.append(txt[index - 2])
    elif(ind == 1 and len(txt) < 4):
        win.append(txt[index - 1])
        win.append(txt[index + 1])
    elif(ind == (len(txt) - 2) and len(txt) >= 4):
        win.append(txt[index + 1])
        win.append(txt[index - 1])
        win.append(txt[index - 2])
    elif(ind >= 2 or ind <= (len(txt) - 3)):
        win.append(txt[index + 1])
        win.append(txt[index + 2])
        win.append(txt[index - 1])
        win.append(txt[index - 2])
    return win
    

    【讨论】:

    • 请检查您的缩进
    【解决方案3】:

    为什么不直接使用 try/except 机制?

    def window_elements(win,ind,txt):
        for i in (1, 2, -1, -2):
            try:
                win.append(txt[index + i])
            except IndexError:
                pass
        return win
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-01-24
      • 2021-05-12
      • 1970-01-01
      • 2016-01-06
      • 2014-11-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多