简体   繁体   English

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

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

I try this: 我尝试这样:

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))

I set up many reverse proxy server for google. 我为Google设置了许多反向代理服务器。 the server list is google_add_list I mean to search all the item in the list with the add i provide and get the result If google block me, the scrape_keyword_count() will return None. 服务器列表是google_add_list,我的意思是搜索列表中所有包含我提供的添加项并获得结果的结果。如果google阻止了我,则scrape_keyword_count()将返回None。 then i And I need to change to another add to do the search. 然后我,我需要更改为另一个添加项来进行搜索。 but the script i wrote will skip the keyword no matter the scrape_keyword_count() success or not 但无论是否scrape_keyword_count()成功与否,我编写的脚本都会跳过关键字

I know removing an item within the for loop is dangerous i will improve this part later 我知道在for循环中删除项目很危险,我稍后会对此部分进行改进

The problem here is that you're modifying the list while iterating over it. 这里的问题是您在迭代列表时正在修改列表。

Use "for i in the_list[:]" instead. 使用“ for the in the_list [:]”代替。 This will iterate over a copy of the list, fixing your "skipping" (missed elements) issue. 这将遍历列表的副本,从而解决“跳过”(缺少元素)的问题。

Perhaps: 也许:

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

If do_something_with(i) succeeded then continue with the next item otherwise do_something_else(i) . 如果do_something_with(i)成功,则继续下一项,否则继续do_something_else(i)

You can't mutate a list while iterating over it. 您不能在迭代列表时对其进行变异。 If the filtered list is needed, rather than removing elements from the old one produce a new one. 如果需要过滤列表,则不是从旧列表中删除元素,而是生成新列表。

The for loop will use each item once... Your code looks fine... But I think you may not be returning the correct value in do_something_with for循环将使用每个项目一次...您的代码看起来不错...但是我认为您可能没有在do_something_with中返回正确的值

Try this: 尝试这个:

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

I think you may always be returning True from do_something_with 我认为您可能总是从do_something_with返回True

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

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