如何在 while 循环中使用异常?列表索引超出范围 [英] How can I use an exception inside an while loop? list index out of range

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

问题描述

我有以下功能:

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

它遍历列表中的推文,并找到转发次数超过 100 的推文.

It loops through tweets from a list, and finds tweets that have more than 100 retweets.

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

The problem is, after a while this often happens:

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

此错误会破坏脚本.

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

How can I make my script not stop when that happens, and run a function that refreshes the list so it doesn't run out of range?

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

I'd like to use something like this inside the while loop:

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

如何在 while 循环中使用 except ?

How would one use an except inside the while loop?

推荐答案

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

While you can make this work, you should be using a for loop:

# 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() 添加了更多推文,您应该阅读 生成器 和迭代器,这是您想要使用的.

If, as can be guessed, refreshTL() adds more tweets, you should read on generators and iterators, which are what you want to be using.

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

A very simple example of an endless tweet generator would be:

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,生成器会不断地重新填充推文.现在您可以执行以下操作:

The generator is constantly re-filled with tweets if you implement fetch_tweets. Now you can do something like:

# 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

这篇关于如何在 while 循环中使用异常?列表索引超出范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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