python培训之如何查找缺失的参数

发布时间:2023-01-07 09:46:10 人气:70 作者:多测师

  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

python培训之如何查找缺失的参数

  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学习指路:请关注多测师。https://www.e70w.com/xwzx/




返回列表
在线客服
联系方式

热线电话

17727591462

上班时间

周一到周五

二维码
线