zoukankan      html  css  js  c++  java
  • Python内置函数(19)-slice

    官方文档

    class slice(stop)
    class slice(start, stop[, step])
    Return a slice object representing the set of indices specified by range(start, stop, step). The start and step arguments default to None. Slice objects have read-only data attributes start, stop and step which merely return the argument values (or their default). They have no other explicit functionality; however they are used by Numerical Python and other third party extensions. Slice objects are also generated when extended indexing syntax is used. For example: a[start:stop:step] or a[start:stop, i]. See itertools.islice() for an alternate version that returns an iterator.
    说明:1.函数实际上是切片类的一个构造函数,返回一个切片对象
             2.切片对象由3个参数组成,start、stop、step组成,start和step默认是None。切片对象主要是对序列对象进行切片取元素
    >>> help(slice)
    
     |      Return repr(self).
     |  
     |  indices(...)
     |      S.indices(len) -> (start, stop, stride)
     |      
     |      Assuming a sequence of length len, calculate the start and stop
     |      indices, and the stride length of the extended slice described by
     |      S. Out of bounds indices are clipped in a manner consistent with the
     |      handling of normal slices.
     |  
     |  ----------------------------------------------------------------------
     |  Data descriptors defined here:
     |  
     |  start
     |  
     |  step
     |  
     |  stop
     |  
     |  ----------------------------------------------------------------------
     |  Data and other attributes defined here:
     |  
     |  __hash__ = None

    li = [11,22,33,44,55,66,77]
    
    ret1 = li[None:5:None]  #start,stem为None
    ret2 = li[:5:] #同上
    print(ret1,ret2)
    #输出
    #[11, 22, 33, 44, 55]  [11, 22, 33, 44, 55]
    
    ret3 = li[2:5:None] #step为None
    ret4 = li[2:5:]
    print(ret3,ret4)    #同上
    #输出
    #[33, 44, 55]
    #[33, 44, 55]
    
    ret5 = li[1:6:3]
    print(ret5)
    #输出
    #[22, 55]

      3.对应切片的3个属性start、stop、step,slice函数也有3个对应的参数start、stop、step,其值会直接赋给切片对象的start、stop、step

    #定义c1
    c1 = slice(5)
    print(c1)
    #输出
    #slice(None, 5, None)
    
    #定义c2
    c2 = slice(2,5)
    print(c2)
    #输出
    #slice(2, 5, None)
    
    #定义c3
    c3 = slice(1,6,3)
    print(c3)
    #输出
    #slice(1, 6, 3)
    
    a = list(range(1,10))
    ret1 = a[c1]   #同a[:5:]一样
    print(ret1)
    #输出
    #[1, 2, 3, 4, 5]
    
    ret2 = a[c2]  #同a[2:5:]一样
    print(ret2)
    #输出
    #[3, 4, 5]
    
    ret3 = a[c3]  #同a[1:6:3]一样
    print(ret3)
    #输出
    #[2, 5]
  • 相关阅读:
    UDP通信网络编程
    多线程:购票小案例
    多线程:线程池异步计算,2个线程,1个计算10的阶乘,一个计算20的阶乘并返回
    Kong入门指南
    5分钟完成App后端API开发
    Docker安装Kong
    React Native如何用调用RestFul API
    Flutter如何用调用RestFul API
    如何用Flutter调用生成的RestFul API
    自动化API之一 生成开源ERP Odoo App 的RestFul API
  • 原文地址:https://www.cnblogs.com/it-q/p/7986558.html
Copyright © 2011-2022 走看看