gpt4 book ai didi

python中的PHP空函数

转载 作者:行者123 更新时间:2023-11-28 16:48:30 26 4
gpt4 key购买 nike

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

$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++;
}

如果我这样做

if a[i] is None

然后我得到索引超出范围。不过,我知道可以通过多个步骤完成此操作的方法,但这不是我想要的。

最佳答案

PHP 数组和 Python 列表是不等价的。 PHP 数组实际上是 associative containers :

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 数据结构定义为 dictionary :

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

empty() 函数 serve many purposes .在您的使用上下文中,它等同于 Python in 运算符:

>>> a = {}
>>> a[1] = "x"
>>> a[3] = "y"
>>> a[5] = "z"
>>> i = 3
>>> i in a
True
>>> i = 2
>>> i in a
False

关于python中的PHP空函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10989297/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com