Python 尝试除非列表为空
Python Try Except when a list is null
我一直在这里寻找我的问题,但找不到我的问题的确切答案。
我调用了一个 sympy 函数( solve() )。此函数可以 return 完整列表或空列表。
我一会儿调用这段代码:
try:
sol = solve([eq1,eq2],[r,s])
rB = bin(abs(sol[0][0]))
sB = bin(abs(sol[0][1]))
stop = True
r = rB[2:len(rB)]
s = sB[2:len(sB)]
P = int("0b"+r+s,2)
Q = int("0b"+s+r,2)
print(P*Q == pubKey.n)
print("P = {}".format(P))
print("Q = {}".format(Q))
break
except ValueError:
pass
我想要的是:
如果 solve() return 是一个空列表,则通过。如果 solve() return 是完整列表,请继续执行。解决方案将是 returning 空列表,直到我找到正确的值。
这可以通过检查 sol[0][0] 来实现,如果有一个非空列表,这将起作用,但如果列表为空,这将抛出一个错误(空指针),我想尝试标记它并通过。
我现在遇到的是,当 sol 为空时,它会尝试获取 sol[0][0],这会抛出一个未被 try 捕获的错误,整个代码将停止。
有人知道解决方案吗?我没有正确使用 try?
在每个循环的开头将 sol 设置为某个值并在 except 子句中检查它
关于else
try/except
有一个 else
这将是 运行 try
块没有引发异常
and for
有一个 else
子句,当它没有被打破时!
for foo in iterable:
# set value so the name will be available
# can be set prior to the loop, but this clears it on each iteration
# which seems more desirable for your case
sol = None
try:
"logic here"
except Exception:
if isinstance(sol, list):
"case where sol is a list and not None"
# pass is implied
else: # did not raise an Exception
break
else: # did not break out of for loop
raise Exception("for loop was not broken out of!")
我一直在这里寻找我的问题,但找不到我的问题的确切答案。 我调用了一个 sympy 函数( solve() )。此函数可以 return 完整列表或空列表。 我一会儿调用这段代码:
try:
sol = solve([eq1,eq2],[r,s])
rB = bin(abs(sol[0][0]))
sB = bin(abs(sol[0][1]))
stop = True
r = rB[2:len(rB)]
s = sB[2:len(sB)]
P = int("0b"+r+s,2)
Q = int("0b"+s+r,2)
print(P*Q == pubKey.n)
print("P = {}".format(P))
print("Q = {}".format(Q))
break
except ValueError:
pass
我想要的是: 如果 solve() return 是一个空列表,则通过。如果 solve() return 是完整列表,请继续执行。解决方案将是 returning 空列表,直到我找到正确的值。 这可以通过检查 sol[0][0] 来实现,如果有一个非空列表,这将起作用,但如果列表为空,这将抛出一个错误(空指针),我想尝试标记它并通过。
我现在遇到的是,当 sol 为空时,它会尝试获取 sol[0][0],这会抛出一个未被 try 捕获的错误,整个代码将停止。 有人知道解决方案吗?我没有正确使用 try?
在每个循环的开头将 sol 设置为某个值并在 except 子句中检查它
关于else
try/except
有一个 else
这将是 运行 try
块没有引发异常
and for
有一个 else
子句,当它没有被打破时!
for foo in iterable:
# set value so the name will be available
# can be set prior to the loop, but this clears it on each iteration
# which seems more desirable for your case
sol = None
try:
"logic here"
except Exception:
if isinstance(sol, list):
"case where sol is a list and not None"
# pass is implied
else: # did not raise an Exception
break
else: # did not break out of for loop
raise Exception("for loop was not broken out of!")