python判断元素在不在数组中_检查数组中是否存在元素

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

有帮助吗?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值