Home > php教程 > php手册 > Python 检查数组元素是否存在 类PHP isset()

Python 检查数组元素是否存在 类PHP isset()

WBOY
Release: 2016-06-06 19:51:10
Original
1910 people have browsed it

PHP中有isset方法来检查数组元素是否存在,在Python中无对应函数。 Python的编程理念是“包容错误”而不是“严格检查”。举例如下: Look before you leap (LBYL): if idx len(array): array[idx]else: #handle this Easier to ask forgiveness than permiss

PHP中有isset方法来检查数组元素是否存在,在Python中无对应函数。

Python的编程理念是“包容错误”而不是“严格检查”。举例如下:

Look before you leap (LBYL):

if idx <br>Easier to ask forgiveness than permission (EAFP):<br><pre class="brush:php;toolbar:false">try:
  array[idx]
except IndexError:
  #handle this
Copy after login

所以在Python中一般可以通过异常来处理数组元素不存在的情况,而无须事先检查。

如果不希望看见异常处理,也可以像下面这样:

if 'test' in ['demo','example']:

    ...

else:

    ...
Copy after login



by iefreer
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template