PHP中的PHP空函数

PHP empty function in python

我有下面的PHP代码,在我的一生中,我想不出一种简单而优雅的方法来围绕python中的empty()函数来实现,以检查索引是否在列表中定义。

1
2
3
4
5
6
7
8
9
10
$counter = 0;
$a = array();
for ($i=0;$i<100;$i++){
  $i = ($i > 4) ? 0 : $i;
  if empty($a[$i]){
    $a[$i]=array();
  }
  $a[$i][] = $counter;
  $counter++;
}

如果我愿意的话

1
if a[i] is None

然后我得到超出范围的索引。然而,我知道如何通过多个步骤来完成它,但这不是我想要的。


php数组和python列表不是等效的。PHP数组实际上是关联容器:

An array in PHP is actually an ordered map. A map is a type that
associates values to keys. This type is optimized for several
different uses; it can be treated as an array, list (vector), hash
table (an implementation of a map), dictionary, collection, stack,
queue, and probably more.

在python中,map数据结构定义为字典:

A mapping object maps hashable values to arbitrary objects. Mappings
are mutable objects. There is currently only one standard mapping
type, the dictionary.

empty()函数有许多用途。在您的使用上下文中,它相当于python in操作符:

1
2
3
4
5
6
7
8
9
10
>>> a = {}
>>> a[1] ="x"
>>> a[3] ="y"
>>> a[5] ="z"
>>> i = 3
>>> i in a
True
>>> i = 2
>>> i in a
False

如果您试图用一个列表来做这个操作,那么实际上必须将该索引设置为"无",否则元素将不存在,您可能会试图检查一个超过列表末尾的索引。

1
2
3
4
5
6
7
8
>>> i = [None]
>>> i
[None]
>>> i = [None, None]
>>> i
[None, None]
>>> i[1] is None
True