【问题标题】:iterate the list in python在python中迭代列表
【发布时间】:2014-04-26 21:46:07
【问题描述】:

我在循环中有一个循环,我正在使用 try n catch 一旦出现错误 try n catch 工作正常,但循环继续到下一个值。我需要的是循环中断从相同的值开始的地方不要继续到下一个,所以我如何用我的代码做到这一点[就像在其他语言中一样:在 c++ 中,它是 i--]

for 
r = urllib2.urlopen(url) 
       encoding = r.info().getparam('charset')
       html = r.read()
c = td.find('a')['href']
urls = []
urls.append(c)
#collecting urls from first page then from those url collecting further info in below loop

    for abc in urls:
       try:
           r = urllib2.urlopen(abc) 
           encoding = r.info().getparam('charset')
           html = r.read()
       except Exception as e:
           last_error = e
           time.sleep(retry_timeout) #here is the problem once get error then switch from next value 

我需要一种更 Pythonic 的方式来做到这一点。 等待答复。谢谢。

【问题讨论】:

  • 欢迎来到 SO!请仅在已知问题非常特定于版本的情况下使用版本号:meta.stackexchange.com/questions/85358/…
  • 请缩进您的代码,以便它是有效的 Python。请告诉我们更多关于trycatch内部发生的事情。
  • 另外,如果你写了整个句子,包括标点符号,那就太好了。拼写是一种奖励。
  • 如果您有for 循环,请将其更改为while 循环,并且仅在try 块中增加ii += 1。另外,我假设您的缩进在实际代码中是正确的。
  • 现在看看上面我在做什么。谢谢

标签: python list python-2.7 web web-scraping


【解决方案1】:

不幸的是,没有简单的方法可以在 Python 中使用迭代器返回:

http://docs.python.org/2/library/stdtypes.html

你应该对这个 stackoverflow 的线程感兴趣: Making a python iterator go backwards?

对于您的特殊情况,我将使用一个简单的 while 循环:

url = []
i = 0
while i < len(url): #url is list contain all urls which contain infinite as url updates every day
    data = url[i]
    try:
        #getting data from there
        i+=1
    except:
        #shows the error received and continue to next loop i need to make the loop start from same position

您想要处理问题的方式的问题是您将冒着陷入无限循环的风险。例如,如果链接损坏 r = urllib2.urlopen(abc) 将始终运行异常并且您将始终停留在同一位置。你应该考虑做这样的事情:

r = urllib2.urlopen(url) 
encoding = r.info().getparam('charset')
html = r.read()
c = td.find('a')['href']
urls = []
urls.append(c)
#collecting urls from first page then from those url collecting further info in below loop
NUM_TRY = 3
for abc in urls:
   for _ in range(NUM_TRY):
       try:
           r = urllib2.urlopen(abc) 
           encoding = r.info().getparam('charset')
           html = r.read()
           break #if we arrive to this line, it means no error occur so we don't need to retry again
                #this is why we break the inner loop
       except Exception as e:
           last_error = e
           time.sleep(retry_timeout) #here is the problem once get error then switch from next value

【讨论】:

  • 嗯,我没有得到前四行,看起来你忘记了删除 for 和一些缩进之类的东西
  • i+=1 是 i = i + 1 的快捷方式,它将使 data = url[i] 转到 url 的下一个元素。
  • @user3387184:您的code looks similar to this。您需要做的就是用for url in urls: 包装for _ in range(max_retries): 块,如@Luc 所示
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-10
  • 1970-01-01
  • 2019-11-28
  • 2014-02-15
  • 1970-01-01
相关资源
最近更新 更多