gpt4 book ai didi

python - 清理 python 切片?

转载 作者:太空宇宙 更新时间:2023-11-03 11:35:08 25 4
gpt4 key购买 nike

我正在使用 Python/ctypes 来包装一个 C 库。我包装的结构之一类似于数值向量,我希望相应 Python 类的 getitem() 方法支持切片。在 C 级别,我有这样的切片感知功能:

void * slice_copy( void * ptr , int index1 , int index2 , int step) {  
...
}

我的 Python getitem() 看起来像这样:

def __getitem__(self , index):  
if isinstance( index , types.SliceType):
# Call slice_copy function ...
# Need values for arguments index1, index2 and step.
elif isinstance( index , types.IntType):
# Normal index lookup
else:
Raise TypeError("Index:%s has wrong type" % index)

如果切片文字看起来像 [1:100:10] 切片对象的开始、结束和步骤属性都已设置,但例如在 [-100:] 的情况下,start 属性将为 -100,end 和 step 属性将为 None,即在我可以将整数值传递给 C 函数 slice_copy() 之前需要对它们进行清理。现在,这种清理不是很困难,但我本以为必要的功能已经包含在 Python 源代码中 - 或者?

最佳答案

界面里确实有功能。 slice 对象有一个 indices() 方法,它接受序列的长度作为参数,并以元组的形式返回规范化的开始、停止和步长值。

关于python - 清理 python 切片?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6246084/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com