• Python 切片


    Python 切片

    什么是切片

    切片是由 : 隔开的两个索引来访问一定范围内的元素。其中, 列表list、元组tuple、字符串string 都可以使用切片.

    • 代码1-1
    colors = ['red', 'green', 'gray', 'black']
    
    print(colors[1 : 3])  # ['green', 'gray']
    
    

    为什么要使用切片

    如果不使用切片,可以通过循环的方式来访问列表某个范围的元素,例如:

    • 代码1-2
    colors = ['red', 'green', 'gray', 'black']
    
    for i in range(len(colors)):
        if i >=1 and i < 3:
            print(colors[i])  # ['green', 'gray']
    

    与前面的代码对比不难发现,使用切片访问一个范围内的元素更加方便

    切片的使用方法

    1. 切片是从序列的左边索引开始到右边索引结束这个区间内取元素(前闭后开);如果比右边的索引值大于左边的索引则取出的是空序列
    • 代码1-3
    colors = ['red', 'green', 'gray', 'black']
    
    print(colors[1 : 3])  # ['green', 'gray']
    print(colors[3 : 1])  # []
    print(colors[1 : 5])  # ['green', 'gray', 'black']
    
    
    1. 切片的索引值可以取负数,则切片方向从序列的尾部开始
    • 代码1-4
    colors = ['red', 'green', 'gray', 'black']
    
    print(colors[-3 : -1])  # ['green', 'gray']
    print(colors[-1 : -3])  # []
    print(colors[-5 : -1])  # ['red', 'green', 'gray']
    
    
    1. 索引值可以省略,左侧默认取最小(正切为0,反切为序列长度的负值)右侧默认取最大(正切为序列长度,反切为0)
    • 代码1-5
    colors = ['red', 'green', 'gray', 'black']
    
    print(colors[ : 1])  # ['red']
    print(colors[1 : ])  # ['green', 'gray', 'black']
    print(colors[-1 : ]) # ['black']
    print(colors[ : -1]) # ['red', 'green', 'gray']
    print(colors[ : ])   # ['red', 'green', 'gray', 'black']
    print(colors[1 : 1]) # []
    
    
    1. 切片步长,可以隔几个元素进行切片,默认的步长为 1; 步长可以为负值,则切片为逆序
    • 代码1-6
    numbers = list(range(1,11))
    print(numbers[1:10:2])  # [2, 4, 6, 8, 10]
    print(numbers[10:2:-2]) # [10, 8, 6, 4]
  • 相关阅读:
    全国哀悼日 灰色CSS滤镜 PENGHAO
    Jmail发信函数 PENGHAO
    XHTML 1.0 参考 PENGHAO
    今天搬家。。 PENGHAO
    JS代码Checkbox控制输入框 PENGHAO
    CSS hack:区分IE6,IE7,firefox PENGHAO
    获取表中新记录(下一条记录)的主键值的存储过程 PENGHAO
    五种提高 SQL 性能的方法 PENGHAO
    [收藏 ]针对IE网页浏览器不同版本解释的CSS或javascript PENGHAO
    小本创业者的致胜法宝! PENGHAO
  • 原文地址:https://www.cnblogs.com/gzyxy/p/11814329.html
Copyright © 2020-2023  润新知