这段代码中的运算符 == 和 * 是用来做什么的?

What are the operators == and * being used for in this code?

我需要了解以下 python 代码片段中运算符的用法。我不熟悉 np.zeros() 语句中 * 的用法。它看起来像 c 中的指针取消引用运算符,但我猜不是。

还有,赋值语句中==的用法是什么?这看起来像是一个相等性测试,但是 TrueFalse 不是 numpy 数组的有效索引。

new_segs = np.zeros((*raw_segs.shape, 3), dtype=np.uint8)
i = 0
for val in [x['handle'] for x in detections]:
    colors = [(255,0,255), (55,0,55), (34,33,87)]
    new_segs[raw_segs == val] = colors[i % len(colors)]

抱歉这个蹩脚的问题。曾尝试寻找答案,但我在搜索运算符用法时得到的答案并不令人满意。

星号*为拆包操作员;它将 raw_segs.shape 扩展为一个值元组。

您对索引的看法不正确:TrueFalse 有效,分别被解释为 1 和 0。试试看:

>>> new_segs = np.array((3.3, 4.4))
>>> new_segs[0]
3.2999999999999998
>>> new_segs[True]
4.4000000000000004
>>> 

星号*解包说明。 numpy 中的 ==boolean mask。您传递的数组应该与另一个 numpy 数组的大小相同,但这会告诉它要包含或不包含数组的哪些元素。

* 解包 shape 元组,允许它与 3 连接以形成更大形状的元组:

In [26]: x = np.zeros((2,3))
In [28]: y = np.zeros((*x.shape, 3))
In [29]: y.shape
Out[29]: (2, 3, 3)

另一种方法:

In [30]: y = np.zeros(x.shape+(3,))
In [31]: y.shape
Out[31]: (2, 3, 3)

In [32]: i,j = x.shape
In [33]: y = np.zeros((i,j,3))
In [34]: y.shape
Out[34]: (2, 3, 3)