【问题标题】:Iterating over list with while and for loop in python - issues在python中使用while和for循环迭代列表 - 问题
【发布时间】:2015-07-30 10:15:46
【问题描述】:

我正在尝试使用姓名列表查询 Twitter API 并获取他们的朋友列表。 API 部分很好,但我不知道如何检查前 5 个名称,提取结果,等待一段时间以遵守速率限制,然后再为接下来的 5 个名称重复,直到列表结束。我遇到问题的代码是这样的:

first = 0
last = 5
while last < 15: #while last group of 5 items is lower than number of items in list#
    for item in list[first:last]: #parses each n twitter IDs in the list#
        results = item 
        text_file = open("output.txt", "a") #creates empty txt output / change path to desired output#
        text_file.write(str(item) + "," + results + "\n") #adds twitter ID, resulting friends list, and a line skip to the txt output#
        text_file.close()
        first = first + 5 #updates list navigation to move on to next group of 5#
        last = last + 5
        time.sleep(5) #suspends activities for x seconds to respect rate limit#

这个脚本不应该遍历列表中的前 5 个项目,将它们添加到输出文件,然后更改 first:last 参数并循环它直到“last”变量为 15 或更高?

【问题讨论】:

    标签: python api for-loop twitter while-loop


    【解决方案1】:

    不,因为你的缩进是错误的。一切都发生在 for 循环中,所以它会处理一个项目,然后首先和最后更改,然后休眠......

    将最后三行移回一个缩进,使它们与for 语句对齐。这样,一旦前五个完成,它们就会被执行。

    【讨论】:

      【解决方案2】:

      Daniel 发现了问题,但这里有一些代码改进建议:

      first, last = 0, 5
      with open("output.txt", "a") as text_file:
          while last < 15:
              for twitter_ID in twitter_IDs[first:last]:
                  text_file.write("{0},{0}\n".format(twitter_ID))
              first += 5 
              last += 5
              time.sleep(5)
      

      如您所见,我删除了 results = item,因为它看起来多余,利用 with open...,还使用 ​​+= 进行增量。

      你能解释一下为什么你在哪里做item = results吗?

      【讨论】:

      • 有趣,感谢您的提示并花时间纠正初学者的错误。至于“item = results”,我在试图找出问题所在时删除了脚本中的 API 部分,所以我最终将其粘贴在这里,因为我认为错误出在其他地方。在原始和更正后的最终脚本中,它是 results = twitter.friends.ids(skip_status="true",include_user_entities="false",count ="5000",user_id=item)
      猜你喜欢
      • 2016-09-04
      • 2010-09-11
      • 1970-01-01
      • 2014-09-17
      • 1970-01-01
      • 1970-01-01
      • 2013-07-21
      • 2011-07-10
      • 1970-01-01
      相关资源
      最近更新 更多