python - 为什么这个 Numpy 函数链中需要命名表达式?

标签 python numpy method-chaining

这段代码:

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/

相关文章:

python - 我有一组不等长的列表,计算每个列表长度的最快方法是什么

python - 并行组装 Numpy 数组

swift - Swift 中的方法和属性链接调用

PHP:链接方法调用

python - 创建子包而不影响全局包

python - 如何将视频转换为 numpy 数组?

python - 在 Python 中使用函数返回子字符串

c++ - 成员函数的链式调用 - 调用顺序

python - 如何将 Lambda CloudFormation 资源中的环境变量用于 python?

python - 如何检测异步中的写入失败?