这段代码:
a = np.arange(12, 0, -1).reshape(3, 4)
(a := a.flatten()).sort()
print(a)
产生
[ 1 2 3 4 5 6 7 8 9 10 11 12]
正如预期的那样。没有命名表达式:
a = np.arange(12, 0, -1).reshape(3, 4)
a = a.flatten().sort()
print(a)
我得到无
。这是为什么?
最佳答案
引用自PEP 572 – Assignment Expressions
Syntax and semantics
In most contexts where arbitrary Python expressions can be used, a named expression can appear. This is of the form NAME := expr where expr is any valid Python expression other than an unparenthesized tuple, and NAME is an identifier.
The value of such a named expression is the same as the incorporated expression, with the additional side-effect that the target is assigned that value:
所以这段代码,
(a := a.flatten()).sort()
print(a)
大致相当于
a = a.flatten()
a.sort()
print(a)
这意味着您没有将 sort
的结果分配到任何地方。您让 a.sort()
完成并稍后打印 a
(这将产生预期的输出)
记住sort
是一个就地操作,它返回None
,所以在你的第二个代码中你分配了的返回值>排序
(即无
)。
a = a.flatten().sort()
关于python - 为什么这个 Numpy 函数链中需要命名表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71923816/