[英]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.