• python切片操作


    序列类型是其元素被顺序放置的一种数据结构类型,这种方式允许通过下标的方式来获得某一个数据元素,或者通过指定下标范围来获得一组序列的元素。这种访问序列的方式叫做切片。字符串也可以使用切片操作。切片操作符:[]  [:]  [::],调用内置函数slice()函数。

    以字符串'abcdefg'为例:

    s

    a

    b

    c

    d

    e

    f

    g

    index

    0

    1

    2

    3

    4

    5

    6

    index

    -7

    -6

    -5

    -4

    -3

    -2

    -1

    一、sequence[index]

    类似于其他语言的数组操作。sequence是序列的名字,index是想要访问的元素对应的偏移量。偏移量正负都可以,-len(sequence)<=index<=len(sequence)-1。正索引以序列的开始为起点,负索引以序列的结束为起点。

    试图访问一个越界的索引会引发一个IndexError异常。

    二、sequence[starting_index:ending_index]

    通过这种方式可以得到从起始索引到结束索引(不包括结束索引所对应的元素)之间的元素,起始索引和结束索引都是可选的,如果没有提供或者用None作为索引值,切片操作会从序列的最开始处开始,或者直到序列的最末尾结束。其中,开始和结束的索引值可以超出字符串长度,如:s[-100:100],返回'abcdefg'.

    用一个:时,starting_index应该小于ending_index,否则返回空字符串。

    复制代码
     1 # 返回整个序列,即 'abcdefg'
     2 s
     3 s[:]
     4 
     5 # 返回 'abc'
     6 s[0:3]
     7 s[:3]
     8 
     9 # 返回 'cde'
    10 s[2:5]
    11 s[:5]
    12 
    13 # 返回 'def'
    14 s[-4:-1]
    复制代码

    三、sequence[starting_index:ending_index:step]

    扩展切片操作,step为步长参数,类似range()里的步长参数。

    得到的序列从starting_index(包含starting_index)开始,每次以步长前进,即starting_index + step,直到ending_index结束。

    执行:

    1 # 返回 'fedc'
    2 s = 'abcdefg'
    3 s[-2:-6:-1]

    (1) starting_index = -2  ending_index = -6   step = -1

    (2) 第一个读sequence[-2],即 'f',第二个读starting_index + step,即 -2+(-1)=-3,sequence[-3],也就是 'e'。

    (3) 按这个顺序继续读,不包括ending_index,即'b',所以s[-2:-6:-1]返回 'fedc'。

    同理,输出s[2:5:2],返回 'ce'。

    有一个经常用到的应用:翻转字符串

    # 输出 'gfedcba'
    1 s =s'abcdefg' 2 print s[::-1]

    转载自:https://www.cnblogs.com/mzct123/p/6031092.html

  • 相关阅读:
    迭代器相关整理
    闭包的功能举例
    函数参数相关整理
    python中进制转换及IP地址转换
    dD Geometry Kernel ( Geometry Kernels) CGAL 4.13 -User Manual
    2D and 3D Linear Geometry Kernel ( Geometry Kernels) CGAL 4.13 -User Manual
    Monotone and Sorted Matrix Search ( Arithmetic and Algebra) CGAL 4.13 -User Manual
    Algebraic Kernel ( Arithmetic and Algebra) CGAL 4.13 -User Manual
    数论中的环概念
    QT的配置及目录结构
  • 原文地址:https://www.cnblogs.com/aliceyang/p/12009766.html
Copyright © 2020-2023  润新知