Skip to main content
 首页 » 编程设计

python之检查和访问数组元素没有错误

2025年05月04日27lovecherry

我有一个数组,我想验证该数组的第二项。我想到了两种方法

  1. 检查数组长度

    if len(array) > 1: 
        # Process for array[1] 
    
  2. 捕获 IndexError 并在 else block 中处理。

    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 many try and except statements. 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