Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/349.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中正确编写嵌套循环_Python_Python 3.x - Fatal编程技术网

在Python中正确编写嵌套循环

在Python中正确编写嵌套循环,python,python-3.x,Python,Python 3.x,我试图写一个循环,吸引人们的推特追随者。因为Twitter一次只返回5K个追随者,所以这个循环应该对每个用户重复,直到它获得所有追随者。而且,因为有时候Twitter会随机返回错误,所以它也应该在失败的情况下重试几次 这是我目前的尝试,它产生了一个无限循环,我不知道如何修复它。我很确定有一种更简单的方法来写它,我只是不知道它是什么 from twitter import Twitter, OAuth, TwitterHTTPError, TwitterStream t = Twitter(aut

我试图写一个循环,吸引人们的推特追随者。因为Twitter一次只返回5K个追随者,所以这个循环应该对每个用户重复,直到它获得所有追随者。而且,因为有时候Twitter会随机返回错误,所以它也应该在失败的情况下重试几次

这是我目前的尝试,它产生了一个无限循环,我不知道如何修复它。我很确定有一种更简单的方法来写它,我只是不知道它是什么

from twitter import Twitter, OAuth, TwitterHTTPError, TwitterStream
t = Twitter(auth=OAuth(access_token_key, access_token_secret, consumer_key, consumer_secret))

next_cursor=-1
while next_cursor!=0:
    for _ in range(5):
        count=1
        try:
            twitter_pull=t.followers.ids(user_id=some_id,cursor=next_cursor)
            followers_list=twitter_pull['ids']
            next_cursor=twitter_pull['next_cursor']
            if next_cursor!=0:
                time.sleep(60)
            break
        except Exception:
            print("Something went wrong: ", Exception)
            count=count+1
            if count>=5:
                break
        time.sleep(120)

我知道有很多关于嵌套循环的问题,但是在阅读了这些问题的答案之后,我想不出如何解决我的问题。

Python没有提供直接从多个循环中断的方法

一种解决方案是将嵌套循环嵌入到特定函数中,并使用return:

def nested_loop(...):
  while next_cursor != 0:
    for _ in range(5):
       if ...:
         return ...
另一种解决方案是引发特定异常:

class CustomError(Exception): pass

try:
  while next_cursor != 0:
    for _ in range(5):
      if ...:
        raise CustomError
except CustomError:
   ...
最后一个解决方案是以巧妙的方式使用continue/break:

while next_cursor != 0:
  for _ in range(5):
    if ...:
      break
  else:
    continue

  # Next line is reached only if break is raised in the for loop
  break

缩进错误,请修复它为什么需要
count
变量?这不正是范围(5)中的
所做的吗?
谢谢,亚历克斯,刚刚修复了它。Barmar,最初我没有使用count变量,但当我遇到异常时,Python进入了无限循环。因此,count变量是我试图将其从循环中分离出来的,但显然不起作用。