Cython - 在 for 循环中使用 "from" 关键字

Cython - use of "from" keyword in for loop

我最近在 for 循环中阅读了 sklearn 的 BallTree class, which is written in Cython, and I came across some bizarre syntax 的一些源代码:

for j from 0 <= j < n_features:
    centroid[j] += this_pt[j]

环顾四周后,我找不到任何有关在 for 循环中使用 from 关键字的文档。事实上,this answer 明确指出 Python 中 from 的唯一用途是在 import_from 子句中。

虽然读起来很奇怪,但我对这行的解释基本上是:

for j in range(n_features):
    ...

...符合 j0 开头且小于 n_features 的条件。奇怪的语法到底有什么好处,它的作用是否与我预期的不同?

这是一个 oldie that was retained for compatibility with pyrex(cython 的前身)。

for i from 0 <= i < n:

等同于

for i in range(n):

您应该注意到它已被弃用。

这是一个遗留表格。

为了向后兼容 Pyrex,Cython 还支持更详细的 for 循环形式,您可能会在遗留代码中找到它:

for i from 0 <= i < n:

取自Cython docs