我有一个数组,我想验证该数组的第二项。我想到了两种方法
检查
数组长度if len(array) > 1: # Process for array[1]捕获
IndexError并在elseblock 中处理。try: array[1] except IndexError: pass else: # Process for array[1]
哪个更好?
如果你有任何其他选择,我准备学习:)
请您参考如下方法:
Python 鼓励 EAFP coding style :
EAFP
Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of manytryandexceptstatements. The technique contrasts with the LBYL style common to many other languages such as C.
这意味着 try/except 完全没问题,但您不必使用 else 子句,只需执行以下操作:
try:
# Process for array[1]
except IndexError:
pass
