• Python的切片


    在列表操作中,支持索引操作,使用[ 索引 ]取出对应索引的值,Python支持正向索引,也支持负向索引。

    alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]
    #            0    1    2    3    4    5    6    7    8    9
    #           -10  -9   -8   -7   -6   -5   -4   -3   -2   -1
    
    print(alphabet[4])      # e 
    print(alphabet[-6])     # e

    Python中所有的有序序列都支持索引和切片,有序序列如:字符串,元组,列表。

    切片返回的结果和切片的类型一致,返回的切片对象是切片对象的子序列。如:对一个列表切片返回一个列表,对字符串进行切片返回一个字符串。
    而且切片是一种浅拷贝。

    li = [‘A’,’B’,’C’,’D’]
    切片的格式: li[ start : end :step]
    start是切片起点索引,end是切片终点索引,但切片结果不包括终点索引的值。step是步长默认是1。

    alphabet = ["a", "b", "c", "d"]
    #            0    1    2    3
    #           -4   -3   -2   -1
    
    print(alphabet[0:3])        # ['a', 'b', 'c']  起点的0可以生省略 相当于alphabet[:3]
    print(alphabet[2:])         # ['c', 'd']    省略end切到最后
    print(alphabet[1:3])        # ['b', 'c']
    print(alphabet[0:4:2])      # ['a', 'c']    从0到3,步长为2

    在step的符号一定的情况下,start和end可以混合使用正向和反向索引。如何确定start和end,他们之间什么关系?

    无论怎样,你都要保证start和end之间有元素间隔,并且和step方向一致,否则会切出空列表。

    step为正,方向为左到右

    alphabet = ["a", "b", "c", "d"]
    #            0    1    2    3
    #           -4   -3   -2   -1
    
    print(alphabet[0:2])
    print(alphabet[0:-2])
    print(alphabet[-4:-2])
    print(alphabet[-4:2])
    
    # 都是['a', 'b']

    step为负,方向为右到左

    alphabet = ["a", "b", "c", "d"]
    #            0    1    2    3
    #           -4   -3   -2   -1
    
    print(alphabet[-1:-3:-1])
    print(alphabet[-1:1:-1])
    print(alphabet[3:1:-1])
    print(alphabet[3:-3:-1])
    
    # 都是['d', 'c']

    step默认为正,方向为左到右,同时,step的正负决定了切片结果的元素采集的先后

    alphabet = ["a", "b", "c", "d"]
    #            0    1    2    3
    #           -4   -3   -2   -1
    
    print(alphabet[-1:-3])
    print(alphabet[-1:1])
    print(alphabet[3:1])
    print(alphabet[3:-3])
    
    # 以上都是空列表

    省略start和end,全切

    alphabet = ["a", "b", "c", "d"]
    #            0    1    2    3
    #           -4   -3   -2   -1
    
    print(alphabet[:])              # ['a', 'b', 'c', 'd']
    print(alphabet[::-1])           # ['d', 'c', 'b', 'a']
  • 相关阅读:
    robotframework安装与配置--学习第一天
    Google chrome浏览器打不开网页,显示ERR_Failed...等问题的解决方法
    解决dos窗口乱码问题
    打印风车旋转效果
    spring Security 得到认证用户名的方法
    spring requestmapping 拦截多个请求
    github多人协同使用。
    Spring boot Security 用于权限管理,用户添加等。
    spring boot上传 下载图片。
    mysql修改数据库编码(数据库字符集)和表的字符编码的方法
  • 原文地址:https://www.cnblogs.com/maple-shaw/p/8331823.html
Copyright © 2020-2023  润新知