如何在while循环中使用异常?列表索引超出范围

时间:2014-12-28 21:28:30

标签: python twitter

我有以下功能:

def findTweetWith100PlusRTs():
    global tweet_main
    while tweet[tweet_main]["retweet_count"] < 100:
        tweet_main += 1

它循环播放列表中的推文,并查找推文超过100次的推文。

问题是,经过一段时间后经常发生这种情况:

File "bot.py", line 41, in findTweetWith100PlusRTs
    while tweet[tweet_main]["retweet_count"] < 100:
IndexError: list index out of range

此错误会破坏脚本。

如何在发生这种情况时让我的脚本不停止,并运行一个刷新列表的功能,使其不会超出范围?

我想在while循环中使用这样的东西:

except IndexError:
    time.sleep(120)
    refreshTL()

如何在while循环中使用except?

2 个答案:

答案 0 :(得分:2)

虽然可以使这项工作正常,但你应该使用for循环:

# this is a proper use of while! :-)
while True:
    for current_tweet in tweet:
        if current_tweet["retweet_count"] < 100:
            # do something with current_tweet
            pass

    time.sleep(120)
    refreshTL() # make sure you put a new list in `tweet[tweet_main]`

如果可以猜到,refreshTL()添加了更多推文,您应该阅读generators和迭代器,这是您想要使用的。

无限推文生成器的一个非常简单的例子是:

def tweets_generator():
    tweets = None
    while True:
        # populate geneartor
        tweets = fetch_tweets()
        for tweet in tweets:
            # give back one tweet
            yield tweet
        # out of tweets, go back to re-populate generator...

如果您实施fetch_tweets,生成器会不断重新填充推文。现在你可以做类似的事情:

# only take tweets that have less than 100 retweets thanks @Stuart
tg = (tweet for tweet tweet_generator() if tweet['retweet_count'] < 100)
for tweet in tg:
    # do something with tweet

答案 1 :(得分:0)

你可以这样做

def findTweetWith100PlusRTs():
    global tweet_main
    while True:
        try:
            if tweet[tweet_main]["retweet_count"] >= 100:
                break
        except IndexError:
            # do something
        tweet_main += 1