繁体   English   中英

在Python中如何确保列表中的项目被成功处理

[英]In Python how to make sure item in a list be processed successfully

我尝试这样:

for k in  keywords_list:
    google_add = random.choice(google_adds_list)
    url = make_up_url(google_add, k, False)
    if scrape_keyword_count(k, useragent_list, url, result_dir):
        keyword_count = scrape_keyword_count(k, useragent_list, url, result_dir)
        all_keyword_count.append(keyword_count)
        print '%s Finish. Removeing it from the list' % k
        keywords_list.remove(k)
    else:
        print "%s may run into problem, removing it from list" % google_add
        google_adds_list.remove(google_add)
        with open(google_adds, 'w') as f:
            f.write('\n'.join(google_adds_list))

我为Google设置了许多反向代理服务器。 服务器列表是google_add_list,我的意思是搜索列表中所有包含我提供的添加项并获得结果的结果。如果google阻止了我,则scrape_keyword_count()将返回None。 然后我,我需要更改为另一个添加项来进行搜索。 但无论是否scrape_keyword_count()成功与否,我编写的脚本都会跳过关键字

我知道在for循环中删除项目很危险,我稍后会对此部分进行改进

这里的问题是您在迭代列表时正在修改列表。

使用“ for the in the_list [:]”代替。 这将遍历列表的副本,从而解决“跳过”(缺少元素)的问题。

也许:

new_list = []
for i in the_list:
    if do_something_with(i):
       continue
    do_something_else(i)
    new_list.append(i)

如果do_something_with(i)成功,则继续下一项,否则继续do_something_else(i)

您不能在迭代列表时对其进行变异。 如果需要过滤列表,则不是从旧列表中删除元素,而是生成新列表。

for循环将使用每个项目一次...您的代码看起来不错...但是我认为您可能没有在do_something_with中返回正确的值

尝试这个:

for i in the_list:
    value = do_something_with(i)
    print bool(value)
    if value:
        the_list.remove(i)
    <etc> <etc>

我认为您可能总是从do_something_with返回True

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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