作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我习惯于看到括号在表达式周围实例化一个元组。但在这段代码中,它们看起来像是允许对运算符表达式的结果调用函数:
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/
我是一名优秀的程序员,十分优秀!