我有一个简单的函数,它将节点之间的键列表转换为相邻节点的列表。输入是“整数元组列表”,输出是“整数列表列表”,例如
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类型list
、tuple
、dict
等不是通用的。它们是基本 *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/