python中index、slice与slice assignment用法

python中index、slice与slice assignment用法

一、index与slice的定义:

  • index用于枚举list中的元素(Indexes enumerate the elements);
  • slice用于枚举list中元素集合(Slices enumerate the spaces between the elements).
  • slice assignment,是一个语法糖,主要用于list的快速插入、替换、删除元素。

二、语法

index

index语法很简单,如下表所示,如有一个list a,a[i]表示a中第i个元素(a[0]表示第一个元素),当i<0时,表示倒数第几个元素(a[-1]表示倒数第一个元素)。

Python indexes and slices for a six-element list.
Indexes enumerate the elements, slices enumerate the spaces between the elements.

Index from rear:    -6  -5  -4  -3  -2  -1      a=[0,1,2,3,4,5]    a[1:]==[1,2,3,4,5]
Index from front:    0   1   2   3   4   5      len(a)==6          a[:5]==[0,1,2,3,4]
                   +---+---+---+---+---+---+    a[0]==0            a[:-2]==[0,1,2,3]
                   | a | b | c | d | e | f |    a[5]==5            a[1:2]==[1]
                   +---+---+---+---+---+---+    a[-1]==5           a[1:-1]==[1,2,3,4]
Slice from front:  :   1   2   3   4   5   :    a[-2]==4
Slice from rear:   :  -5  -4  -3  -2  -1   :
                                                b=a[:]
                                                b==[0,1,2,3,4,5] (shallow copy of a)

slice

slice的基本形式为a[start : end : step],这三个参数都有默认的缺省值,但是为了与index区别,slice语法中至少要有一个:,对缺省值的理解是正确使用slice的关键,可以用一下几条来说明:

  1. step的默认值为1,若step > 0表示从前向后枚举,step < 0则相反,step不能为0;

  2. start、end的默认值与step值的正负相关,可见下表:

    -------------------------
    step  |  +   |  -       |
    -------------------------
    start |  0   |  -1      |
    end   |  len |  -(len+1)|
    -------------------------
    
  3. step和end中的负值都可以通过加上len得到其正值,有别于range(start,end)。

slice assignment

a[start : end : step] = b与b = a[start : end : step]不同,后者是在list a中取出一些元素,然后重新组成一个新的list给b,不会改变list a的值;而前者直接改变a的值。其主要用法有:

  1. 插入
>>> a = [1, 2, 3]
>>> a[0:0] = [-3, -2, -1, 0]
>>> a
[-3, -2, -1, 0, 1, 2, 3]
  1. 删除
>>> a
[-3, -2, -1, 0, 1, 2, 3]
>>> a[2:4] = []
>>> a
[-3, -2, 1, 2, 3]
  1. 替换
>>> a
[-3, -2, 1, 2, 3]
>>> a[:] = [1, 2, 3]
>>> a
[1, 2, 3]

引用:

--http://stackoverflow.com/questions/10623302/how-assignment-works-with-python-list-slice/10623352#10623352

--http://stackoverflow.com/questions/509211/explain-pythons-slice-notation

原文地址:https://www.cnblogs.com/keviwu/p/5878180.html