开发者

How come my function is only looping through three elements within my list

I am trying to loop through all the elements (8 of them) in my list, but my function is only providing me with 4 of them. This is for an application I am making as a personal project.

import urllib


def get_followers():
    count = 0
    link = ['http://twitter.com/statuses/user_timeline.xml?screen_name=beratmahmuzlu',     'http://twitter.com/statuses/user_timeline.xml?screen_name=lidiazuin', 'http://twitter.com/statuses/user_timeline.xml?screen_name=kelewele_boham', 'http://twitter.com/statuses/user_timeline.xml?screen_name=AwangHafizam', 'http://twitter.com/statuses/user_timeline.xml?screen_name=BRAYANLVN', 'http://twitter.com/statuses/user_timeline.xml?screen_name=zezol_开发者_JS百科pl', 'http://twitter.com/statuses/user_timeline.xml?screen_name=brysonwong', 'http://twitter.com/statuses/user_timeline.xml?screen_name=racsozara']
    while count < len(link):
        print link[count]
        link.pop()
        count = count + 1


You are popping the list and basing your loop off of the count of the list.

try a for loop instead:

for lnk in link:
    print lnk


link.pop() removes an element and len(link) gives you the new length of the list at each iteration, looping thus thru only the half of your list.

def get_followers():
    count = 0
    link = [0, 1, 2, 3, 4, 5, 6, 7, 8]
    l = len(link)
    while count < l:
        print link.pop()
        count = count + 1

This is the correct implementation, although there are many more cleaner way to iterate over a list in python, this is one of the simplest:

def get_followers():
    link = [0, 1, 2, 3, 4, 5, 6, 7, 8]
    for l in link:
        print l


I am trying to loop through all the elements (8 of them) in my list

Then do that. Don't set up a counter variable, repeatedly use it to index into the list, remove elements from the list and increment the counter. Just loop through the elements.

If I asked you to crack a dozen eggs, you would not need to write numbers on them, or think about how many eggs you'd already cracked. You'd just do it.

So just do it.

for link in links:
    print link
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜