zl程序教程

您现在的位置是:首页 >  后端

当前栏目

【说站】python如何查找缺失的参数

Python 如何 参数 查找 缺失
2023-06-13 09:13:22 时间

python如何查找缺失的参数

说明

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查找缺失参数的方法,希望对大家有所帮助。