EAFP与LBYL
我理解您的困境,但Python不是PHP,而且称为的编码风格比请求许可更容易请求原谅(简而言之,EAFP)是Python中常见的编码风格。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-catch语句并不是最后的办法;这是一种常见的做法。
Python中的“数组”
PHP有关联和非关联数组,Python有列表、元组和字典。列表类似于非关联PHP数组,字典类似于关联PHP数组。
如果要检查“key”是否存在于“array”中,必须首先告诉Python中的类型,因为当“key”不存在时,它们会抛出不同的错误:>>> l = [1,2,3]
>>> l[4]
Traceback (most recent call last):
File "", line 1, in
l[4]
IndexError: list index out of range
>>> d = {0: '1', 1: '2', 2: '3'}
>>> d[4]
Traceback (most recent call last):
File "", line 1, in
d[4]
KeyError: 4
如果您使用EAFP编码风格,您应该适当地捕捉这些错误。
LBYL编码风格-检查索引的存在性
如果您坚持使用LBYL方法,以下是您的解决方案:对于列表,只需检查长度,如果存在possible_index < len(your_list),则your_list[possible_index],否则不会:>>> your_list = [0, 1, 2, 3]
>>> 1 < len(your_list) # index exist
True
>>> 4 < len(your_list) # index does not exist
False
对于字典可以使用in关键字,如果possible_index in your_dict,则your_dict[possible_index]存在,否则:>>> your_dict = {0: 0, 1: 1, 2: 2, 3: 3}
>>> 1 in your_dict # index exists
True
>>> 4 in your_dict # index does not exist
False
有帮助吗?