python - 如何在 cython 中指定列表和元组类型

标签 python optimization types cython

我有一个简单的函数,它将节点之间的键列表转换为相邻节点的列表。输入是“整数元组列表”,输出是“整数列表列表”,例如

 input:  bonds     = [(1,2), (1,4)]
 output: neighbors = [[],[2,4],[1],[],[1]]

我可以做些什么来更精确地指定这些类型,以便 Cython 可以更好地优化它吗?该函数如下所示:

def bonds2neighs( list bonds, int natom ):
    cdef:
        int  ii
        list neighbors = [ [] for ii in xrange(natom) ]
        int i,j
    for i,j in bonds: 
        neighbors[i].append(j)
        neighbors[j].append(i)
    return neighbors

最佳答案

内置的Python类型listtupledict等不是通用的。它们是基本 *PyObject 的容器。您不能指定诸如 list[tuple[int, int]] 这样的类型,因为不存在这样的东西。

Cython 对准泛型的唯一支持是 fused types 。它们类似于模板和联合的混合,允许预先指定一组固定的可能类型。但是,它们不能与扩展类型一起使用,因此不允许创建通用容器。

Fused types are not currently supported as attributes of extension types. Only variables and function/method arguments can be declared with fused types.

关于python - 如何在 cython 中指定列表和元组类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57371077/

相关文章:

python - 优化忽略某些标签值的损失函数

mongodb - 在 mongodb 中删除重复文档的最快方法

typescript - 带有 typescript 的 React 路由器 v5 上所需的 url 参数,可以是未定义的

python - 错误的 Python 日期计算。

python - 如何关闭与azure服务总线队列的连接?

c++ - 最准确的线相交坐标计算与 float ?

python - 为什么在 python3 中不检查返回类型?

javascript - 使用未定义和 null 的 Object.prototype.toString 函数

python - 如何使用 pywin32 知道窗口是否最大化?

python - 从文件中读取小端并转换为十进制