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]
  • 相关阅读:
    ArcGIS for Android地图控件的5大常见操作
    adb开启不了解决方案
    Eclipse中通过Android模拟器调用OpenGL ES2.0函数操作步骤
    解决 Your project contains error(s),please fix them before running your application问题
    二路归并算法实现
    字符串全排列
    python连接MySQL
    .net常考面试题
    win7 web开发遇到的问题-由于权限不足而无法读取配置文件,无法访问请求的页面
    int.Parse()与int.TryParse()
  • 原文地址:https://www.cnblogs.com/gzyxy/p/11814329.html
Copyright © 2011-2022 走看看