Home  >  Q&A  >  body text

python - How to add time or speed control when traversing a list?

def dateRange(start, end, step=1, format="%Y-%m-%d"):
    strptime, strftime = datetime.datetime.strptime, datetime.datetime.strftime
    days = (strptime(end, format) - strptime(start, format)).days
    return [strftime(strptime(start, format) + datetime.timedelta(i), format) for i in xrange(0, days, step)]
ef weekend():
    try:
        dayday = dateRange(st, ed)

        for day in dayday:
            d =day.replace('-','')
            date = d
            server_url = "http://www.easybots.cn/api/holiday.php?d="

            vop_url_request = urllib2.Request(server_url + date)
            vop_response = urllib2.urlopen(vop_url_request)

            vop_data = json.loads(vop_response.read())

            if vop_data[date] == '1' or vop_data[date] == '2':
                dayday.remove(day)

        return dayday

    except:
        dayday = dateRange(st, ed)
        return dayday

There is such a weekend function to request some content, but some content will be missing every time it is executed. It is suspected to be a problem with the network speed. How to limit the frequency of traversal or access once in a few seconds?

天蓬老师天蓬老师2683 days ago707

reply all(2)I'll reply

  • typecho

    typecho2017-06-14 10:55:10

    After each iteration, add a sleep time

    time.sleep(1) # 睡眠1秒

    That is, your code can be adjusted to:

    for day in dayday:
        ...(访问处理代码)
        time.sleep(1)
        

    reply
    0
  • 学习ing

    学习ing2017-06-14 10:55:10

    I found the problem. The remove operation on the original list during traversal will change the length of the list, which will lead to misalignment of the list. The final result is not the desired result

    reply
    0
  • Cancelreply