ITPub博客

首页 > IT职业 > IT图书 > python如何查找缺失的参数

python如何查找缺失的参数

IT图书 作者:jmctian 时间:2021-09-11 09:47:39 0 删除 编辑

说明

1、如果在切片时遗漏了任何参数,Python将尝试自动计算。

2、如果检查CPython的源代码,会发现一个函数叫做PySlice_GetIndicesEx(),它计算任何给定参数的切片索引。

它是Python中的逻辑等效代码。

该函数使用Python对象和可选参数进行切片,并返回切片的开始、停止、步长和长度。

实例

def py_slice_get_indices_ex(obj, start=None, stop=None, step=None):
 
    length = len(obj)
 
    if step is None:
        step = 1
    if step == 0:
        raise Exception("Step cannot be zero.")
 
    if start is None:
        start = 0 if step > 0 else length - 1
    else:
        if start < 0:
            start += length
        if start < 0:
            start = 0 if step > 0 else -1
        if start >= length:
            start = length if step > 0 else length - 1
 
    if stop is None:
        stop = length if step > 0 else -1
    else:
        if stop < 0:
            stop += length
        if stop < 0:
            stop = 0 if step > 0 else -1
        if stop >= length:
            stop = length if step > 0 else length - 1
 
    if (step < 0 and stop >= start) or (step > 0 and start >= stop):
        slice_length = 0
    elif step < 0:
        slice_length = (stop - start + 1)/(step) + 1
    else:
        slice_length = (stop - start - 1)/(step) + 1
 
    return (start, stop, step, slice_length)

以上就是python查找缺失参数的方法,希望对大家有所帮助。更多Python学习指路:python基础教程

本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/2963/viewspace-2828524/ ,如需转载,请注明出处,否则将追究法律责任。

上一篇: php怎么去除斜线
请登录后发表评论 登录
全部评论

注册时间:2019-08-13

  • 博文量
    0
  • 访问量
    429