我正在尝试创建一个可以制作列表的任意切片的函数,例如:
def slice(arr, a, b, step):
return arr[a:b:step]
问题是,如果用户想要切片 arr[5:] 或 arr[:5] ,如何处理?
最佳答案
在切片中省略一个值相当于使用None
,所以我可能建议这个函数签名:
def slice_(arr, start=None, stop=None, step=None):
return arr[start:stop:step]
建议不要为您的函数使用名称 slice
,因为它会遮蔽 the built-in class 。
注意:您不需要为此功能定义自己的函数。使用动态输入来切片对象的一种更 Pythonic 的方法是直接使用 getitem:
arr[slice(a,b,step)]
关于python 使用函数进行任意切片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49437653/