[英]Python multiple lists loop continue after exception only with one of the lists
我有以下問題:我想遍歷 2 個長度不等的列表。 我正在使用try-except。 有沒有辦法在異常后繼續循環其中一個變量,同時保留未受影響的變量。
try:
for url,proxy in ([proxy1, proxy2,..],[url1, url2,..])
call url by proxy
except #if proxy does not respond an exception is thrown by selenium:
continue loop with proxy[1] and url[0]
您可以像這樣使用zip_longest :
import itertools
for f, g in itertools.zip_longest(i, j):
do_things(f, g)
在do_things
中,您可以處理f
或g
為None
的情況。
如果您想始終使用較短列表中的最后一個元素處理列表,只需將其傳遞給zip_longest
:
fill = i[-1] if len(i) < len(j) else j[-1]
for f, g in itertools.zip_longest(i, j, fillvalue=fill):
do_things(f, g)
您可以為下一次迭代保存值。 例如:
import itertools
lst1 = [2, 4, 6, 8]
lst2 = [2, 0, 2]
for i, j in itertools.zip_longest(lst1, lst2):
try:
print(i / j)
# Save the value
j_ = j
except:
print(i / j_)
Output:
1.0
2.0
3.0
4.0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.