Python - IndexError:列表索引超出范围,即使检查是否为空

时间:2018-05-14 03:39:01

标签: python del index-error

我在以下代码行中得到IndexError:list index超出范围:

if tweetSplit[i] != "":

在我的代码中:

tweetSplit = tweet.split(' ') 

for i in range(len(tweetSplit)):
    #print (i)
    if not tweetSplit:
        break
    if tweetSplit[i] != "":
         #print (tweetSplit[i])
         #print (tweetSplit[i][:1])
        if tweetSplit[i][:1] == '@':
            del tweetSplit[i]

我想通过检查tweetSplit是否为空,使用"如果不是tweetSplit"我不会遇到超出范围的错误。 这是完整的错误:

Traceback (most recent call last):
  File "parseTweets.py", line 55, in <module>
     if tweetSplit[i] != "":
IndexError: list index out of range

3 个答案:

答案 0 :(得分:0)

由于这个问题,你得到IndexError

del tweetSplit[i]

您正在删除tweetSplit内的元素。这会导致tweetSplit缩短长度。

要解决此问题,请不要删除tweetSplit中的任何元素。只需遍历列表即可。无需删除任何元素。

如果您不需要处理任何索引,则只需在Python中使用for-each循环。

for tweet in tweetSplit:
    if tweet != "" and tweet[:1] == '@':
        # Do something but don't delete any tweet from tweetSplit.

答案 1 :(得分:0)

你的考试并没有多大帮助。

确定if not tweetsplit:检查tweetsplit是否为空。但它不会检查tweetsplit是否至少i+1个元素。

并且,因为您在循环中间从tweetsplit删除,如果您删除一个元素,那么,到最后,它将短于i+1,并且提出IndexError

这是您在循环任何集合时不应删除或插入的原因之一。 (但不是唯一的一个 - 例如,当您删除元素i时,会将所有其他元素移到一个插槽中,然后检查新元素i+1,该元素原来是i+2 ......这意味着你错过了一个。)

如果您想构建符合某条规则的所有推文的集合,可以通过构建新列表来更轻松地做到这一点:

goodTweets = []
for tweet in tweetSplit:
    if tweet[:1] != '@':
        goodTweets.append(tweet)

或者:

goodTweets = [tweet for tweet in tweetSplit if tweet[:1] != '@']

如果你真的需要因为某种原因需要改变tweetSplit,你可以使用一些技巧,但它们都有点难看。

构建新列表,然后将tweetSplit更改为该列表:

tweetSplit[:] = [tweet for tweet in tweetSplit if tweet[:1] != '@']

或者,在没有明确构建新列表的情况下执行此操作:

tweetSplit[:] = (tweet for tweet in tweetSplit if tweet[:1] != '@')

或向后迭代。虽然len(tweetSplit)可能会在您删除时发生变化,但0永远不会。 (虽然来自i:的所有内容的位置可能会发生变化,但:i的位置永远不会发生。)

for i in range(len(tweetSplit))[::-1]:
    if tweetSplit[i][:1] == '@':
        del tweetSplit[i]

但是,如果您尝试作为性能优化就地执行此操作,则所有这些通常都会变慢。唯一可能更快的是这样的事情:

i = 0
while i < len(tweetSplit):
    if tweetSplit[i][:1] == '@':
        tweetSplit[i] = tweetSplit[-1]
        tweetSplit.pop()
    else:
        i += 1

答案 2 :(得分:-1)

如果您不确定此时tweetSplit [i]是否在范围内,您可以使用以下内容:

if isinstance(tweetSplit[i], str):

如果tweetSplit [i]的值是string类型,则返回一个布尔值。

通过从tweetSplit数组中删除值的方式,您可能会遇到索引编码问题。