Python 检查数组元素是否存在类似PHP isset()方法,pythonisset


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

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

复制代码 代码如下:

Look before you leap (LBYL):

if idx < len(array):
array[idx]
else:
#handle this

Easier to ask forgiveness than permission (EAFP):


try:
array[idx]
except IndexError:
#handle this

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

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

复制代码 代码如下:

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

...

else:

...


php怎判断数组的某个元素是否存在

isset是判断赋值没有啊,php判断不了一个变量是否存在吧,应为只要$后就是一个变量了
 

PHP怎检查一个数组内是否存在指定元素

用in_array函数 可以判断数组中是否存在一个值

in_array
(PHP 4, PHP 5)

in_array -- 检查数组中是否存在某个值
说明
bool in_array ( mixed needle, array haystack [, bool strict] )

在 haystack 中搜索 needle,如果找到则返回 TRUE,否则返回 FALSE。

如果第三个参数 strict 的值为 TRUE 则 in_array() 函数还会检查 needle 的类型是否和 haystack 中的相同。

注: 如果 needle 是字符串,则比较是区分大小写的。

注: 在 PHP 版本 4.2.0 之前,needle 不允许是一个数组。

例子 1. in_array() 例子

<?php
$os = array("Mac", "NT", "Irix", "Linux");
if (in_array("Irix", $os)) {
echo "Got Irix";
}
if (in_array("mac", $os)) {
echo "Got mac";
}
?>

第二个条件失败,因为 in_array() 是区分大小写的,所以以上程序显示为:

Got Irix

例子 2. in_array() 严格类型检查例子

<?php
$a = array('1.10', 12.4, 1.13);

if (in_array('12.4', $a, true)) {
echo "'12.4' found with strict check\n";
}
if (in_array(1.13, $a, true)) {
echo "1.13 found with strict check\n";
}
?>

上例将输出:

1.13 found with strict check

例子 3. in_array() 中用数组作为 needle

<?php
$a = array(array('p', 'h'), array('p', 'r'), 'o');

if (in_array(array('p', 'h'), $a)) {
echo "'ph' was found\n";
}
if (in_array(array('f', 'i'), $a)) {
echo "'fi' was found\n";
}
if (in_array('o', $a)) {
echo "'o' was found\n";
}
?>

上例将输出:

'ph' was found
'o' was found
参考资料:http;/&#4......余下全文>>
 

评论关闭