簡體   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