简体   繁体   中英

Iterating over list with while and for loop in python - issues

I'm trying to query the Twitter API with a list of names and get their friends list. The API part is fine, but I can't figure out how to go through the first 5 names, pull the results, wait for a while to respect the rate limit, then do it again for the next 5 until the list is over. The bit of the code I'm having trouble is this:

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#

Shouldn't this script go through the first 5 items in the list, add them to the output file, then change the first:last argument and loop it until the "last" variable is 15 or higher?

No, because your indentation is wrong. Everything happens inside the for loop, so it'll process one item, then change first and last, then sleep...

Move the last three lines back one indent, so that they line up with the for statement. That way they'll be executed once the first five have been done.

Daniel found the issue, but here are some code improvements suggestions:

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)

As you can see, I removed the results = item as it seemed redundant, leveraged with open... , also used += for increments.

Can you explain why you where doing item = results?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM