在 python 中使用列表时索引超出范围错误 [英] index out of range error while working with lists in python

查看:34
本文介绍了在 python 中使用列表时索引超出范围错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的项目目的编写一个 python 代码,我想在其中实现窗口机制(目标词的周围词),我已经用下面给出的 axample 列表为它编写了以下部分.当目标词的两侧没有被至少两个词包围时,我得到索引超出范围".

I am writing a python code for my project purpose in which I want to implement windowing mechanism (surrounding words of a target word) and I have written following part for it with an axample lists given below. I am getting "Index out of range" when target word is not surrounded by minimum two words on both the sides.

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 的左侧没有单词,因此该列表将不包含任何内容,它只会从右侧取两个单词并正确执行.
我想要这种机制,但无法以上述方式实现.谁能建议我可以满足我的要求的可选机制?

Suppose here for first execution of for loop target word is 'dog' so from function window_element I want a list of words 2 from the right side of 'dog' and 2 from left side of 'dog'. But here there are no words on the left side of dog so that list will not contain anythong for it and it will take two words from right side only and execute properly.
I want this mechanism but unable to do it in above manner. Can anyone suggest me optional mechanism which will fulfill my requirement?

推荐答案

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

You can try following function. It will work fine.

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

这篇关于在 python 中使用列表时索引超出范围错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆