为什么我的函数只循环列表中的三个元素
我试图循环遍历列表中的所有元素(其中 8 个),但我的函数只为我提供其中 4 个。这是我作为个人项目制作的应用程序。
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_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
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_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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您正在弹出列表并根据列表的计数进行循环。
尝试使用 for 循环:
You are popping the list and basing your loop off of the count of the list.
try a for loop instead:
link.pop() 删除一个元素,而 len(link) 在每次迭代时为您提供列表的新长度,因此仅循环列表的一半。
这是正确的实现,尽管有许多更简洁的方法可以在 python 中迭代列表,但这是最简单的方法之一:
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.
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:
然后执行此操作。不要设置计数器变量,重复使用它来索引列表、从列表中删除元素并递增计数器。只需循环遍历元素即可。
如果我让你打碎一打鸡蛋,你不需要在上面写数字,也不需要考虑你已经打碎了多少个鸡蛋。你就这么做吧。
所以就这么做吧。
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.