zoukankan      html  css  js  c++  java
  • 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]
  • 相关阅读:
    java后台对上传的图片进行压缩
    Reflections框架,类扫描工具
    commons-httpclient和org.apache.httpcomponents的区别
    sql里面插入语句insert后面的values关键字可省略
    Callable接口、Runable接口、Future接口
    Java多线程之Callable接口的实现
    说说Runnable与Callable
    论坛贴吧问题:如何终止运行时间超时的线程
    使用Future停止超时任务
    spring的@Transactional注解详细用法
  • 原文地址:https://www.cnblogs.com/gzyxy/p/11814329.html
Copyright © 2011-2022 走看看