Checking and accessing array element without error
我有一个数组,我想验证它,该数组的第二项。我想有两种方法
检查
1 2 | if len(array) > 1: # Process for array[1] |
捕获
1 2 3 4 5 6 | try: array[1] except IndexError: pass else: # Process for array[1] |
号
哪一个更好?
如果你还有其他选择,我准备好学习了:)
Python encourages 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 manytry andexcept
statements. The technique contrasts with the LBYL style common to many
other languages such as C.
这意味着
1 2 3 4 | try: # Process for array[1] except IndexError: pass |
如果你的阵列至少有2个项目,我会说:
ZZU1
如果您的阵列可能有2个项目,我会使用第一种形式:
1 2 | if len(array) > 1: # Process for array[1] |
对我来说,如果你需要在"阵列处理"中找到例外,那么在长时间的运行中尝试的形式可能是不现实的。