gpt4 book ai didi

python - 对运算符表达式的结果调用函数? (掩码==instance_id).astype(np.uint8)

转载 作者:行者123 更新时间:2023-12-01 00:41:56 25 4
gpt4 key购买 nike

我习惯于看到括号在表达式周围实例化一个元组。但在这段代码中,它们看起来像是允许对运算符表达式的结果调用函数:

img = np.random.rand(100,100)
img = img * 100
img = np.round(img)
val = 15
binary_mask = (val == i).astype(np.uint8)

有人能解释一下这段代码的最后一行吗?为什么 (val == i) 不被解释为元组?

最佳答案

要让 Python 认识到括号内的表达式是一个包含一个元素的元组,您需要在其后面添加 ,:

binary_mask = (val == i,).astype(np.uint8)

否则它只会被解释为带括号的表达式。 (这样的字符串是不明确的,因此 Python 自然地按照最常用的方式对其进行解析,并为您提供了一种明确的方式来指示另一个字符串。)

引用 Python docs 来支持上述内容

A special problem is the construction of tuples containing 0 or 1 items: the 
syntax has some extra quirks to accommodate these. Empty tuples are
constructed by an empty pair of parentheses; a tuple with one item is
constructed by following a value with a comma (it is not sufficient to enclose
a single value in parentheses). Ugly, but effective.

关于python - 对运算符表达式的结果调用函数? (掩码==instance_id).astype(np.uint8),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57279797/

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