繁体   English   中英

Python 多个列表循环仅在列表之一出现异常后继续

[英]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中,您可以处理fgNone的情况。

如果您想始终使用较短列表中的最后一个元素处理列表,只需将其传递给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.

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