zoukankan      html  css  js  c++  java
  • python 列表、元组 详解

    python中有6种序列的内置类型,分别为:列表元组字符串Unicode字符串buffer对象xrange对象

    列表和元组是最常见两种类型。

    下面将以列表(list)和元组(tuple)为例对序列操作进行详细的讲解:

    一、列表(list)

     列表序列操作有:索引、切片、修改、追加、插入、删除、扩展、统计、排序(翻转)、获取下标、拷贝

    1. 索引 (list[i])

     列表的索引序号(又称为下标)如下图所示,该序列一共拥有n个元素,

      从左到右索引是从 0 开始,  n-1 为最后一个元素

      从右到左索引是从 -1开始, -n 为第一个元素

    animals = ['Dog', 'Cat', 'Monkey', 'Chook', 'Snake']
    animals[0]      # 'Dog'
    animals[3]      # 'Chook'
    animals[-1]     # 'Snake'
    animals[-3]     # 'Monkey'
    type(animals[1])    # <class 'str'>

     注意:通过索引取出的元素类型为 str

    2. 切片 (list[a:b])

      索引只能取出python列表中的一个元素,此外,python为取多个列表元素提供了强大的切片操作,通过冒号(:)分割的两个索引来实现

      注意点:

      1. 切片的索引界限可以利用谚语 “顾头不顾尾” 来记忆,也可以理解为数学中的左闭右开,数学式为: [a, b)

      2. 如果省略分隔符前面的索引值,如list[:b],则表示为从第一个元素开始索引,数学式为:[0,b)

          如果省略分隔符后面的索引值,如list[a:],则表示为从a开始索引,索引到最后一个元素结束,此时表现为 “顾头又顾尾”,数学式为[a,end]

      如果两个索引值全部省略不写,list[:],此时表示取整个列表

     3. 列表可以按照某种规则索引元素,如list[first:end:step],frist和end索引与前面的a,b一样,step表示步长,此方法常用于循环中

    animals = ['Dog', 'Cat', 'Monkey', 'Chook', 'Snake']
    animals[1:3]    # ['Cat', 'Monkey']
    animals[3:]     # ['Chook', 'Snake']
    animals[:3]     # ['Dog', 'Cat', 'Monkey']
    animals[:]      # 整个列表
    animals[1:4:2]  # ['Cat', 'Chook']
    animals[::2]    # ['Dog', 'Monkey', 'Snake']

    3. 修改 

    animals = ['Dog', 'Cat', 'Monkey', 'Chook', 'Snake']
    animals[3] = 'Horse'       #将下标为3的元素修改为 'Horse'
    print(animals)

    输出

    ['Dog', 'Cat', 'Monkey', 'Horse', 'Snake']

    4. 追加 (list.append(elem))

     append只能追加一个元素,而且只能追加到列表的最后

    animals = ['Dog', 'Cat', 'Monkey', 'Chook', 'Snake']
    animals.append('Ox')     # 向列表追加元素
    print(animals)
    
    fish = ['freshwater_fish', 'saltwater_fish']     # 鱼(淡水鱼和咸水鱼)
    animals.append(fish)       # 将鱼追加到 animals 列表里
    print(animals)

    输出:

    ['Dog', 'Cat', 'Monkey', 'Chook', 'Snake','Ox']
    ['Dog', 'Cat', 'Monkey', 'Chook', 'Snake','Ox', ['freshwater_fish', 'saltwater_fish']]

    5. 插入 (list.inset(i, elem))

     i代表位置,elem代表元素

    animals = ['Dog', 'Cat', 'Monkey', 'Chook', 'Snake']
    animals.insert(3, 'Horse')
    print(animals)
    
    fish = ['freshwater_fish', 'saltwater_fish']
    animals.insert(-4, fish)
    print(animals)

    输出:

    ['Dog', 'Cat', 'Monkey', 'Horse', 'Chook', 'Snake']
    ['Dog', 'Cat', ['freshwater_fish', 'saltwater_fish'], 'Monkey', 'Horse', 'Chook', 'Snake']

    6. 删除

       删除分为删除元素和删除整个列表

       删除元素的命令有:del,remove,pop

       del list[i]                

       list.remove(elem)            

       list.pop()

    >>>animals
    ['Dog', 'Cat', ['freshwater_fish', 'saltwater_fish'], 'Monkey', 'Horse', 'Chook', 'Snake']
    >>>del animals[2]
    >>>animals
    ['Dog', 'Cat', 'Monkey', 'Horse', 'Chook', 'Snake']
    >>>
    >>>animals.remove('Chook')      # 删除指定元素
    >>>animals
    ['Dog', 'Cat', 'Monkey', 'Horse', 'Snake']
    >>>
    >>>animals.pop()        # 删除最后一个元素
    'Snake' 
    >>>animals
    >>>['Dog', 'Cat', 'Monkey', 'Horse']

    删除整个列表:

    del animals     #删除整个列表

    7. 扩展  ( list.extend(new_list) )

     扩展是将一个列表追加到另一个列表,组成一个新的列表

    animals = ['Dog', 'Cat', 'Monkey', 'Chook', 'Snake']
    fish = ['freshwater_fish', 'saltwater_fish']    
    animals.extend(fish)      # 将fish列表追加到animals列表后,组成一个新的列表
    print(animals)

    输出:

    ['Dog', 'Cat', 'Monkey', 'Chook', 'Snake', 'freshwater_fish', 'saltwater_fish']

    注意下面的情况:

    animals = ['Dog', 'Cat', 'Monkey', 'Chook', 'Snake']
    animals.extend('fish')      
    print(animals)

    输出:

    ['Dog', 'Cat', 'Monkey', 'Chook', 'Snake', 'f', 'i', 's', 'h']

    8. 统计  list.count(elem)

     统计元素出现的次数

    >>>animals = ['Dog', 'Cat', 'Monkey', 'Chook', 'Snake', 'Dog']
    >>>animals.count('Dog')
    2
    >>>animals.count('Cat')
    1
    >>>animals.count('fish')
    0
    >>>
    >>>cat = 'Cat'
    >>>animals.count(cat)
    1

    9. 排序(翻转)

    排序:

      list.sort(self, key=None, reverse=False)

      key 可以为int,str, len, lambda等

      reverse可以为True和False

    数字情况: 默认从小到大排列

    >>> aa = [234, 23, 2, 123]
    >>> aa.sort()          # 数字从小到大排列
    >>> aa                   # 列表的顺序改变了
    [2, 23, 123, 234]
    >>> aa = [234, 23, 2, 123]
    >>> aa.sort(reverse=True)      # 默认从小到大排列,然后转置了
    >>> aa
    [234, 123, 23, 2]
    >>> aa.sort(key=len)              # 数字不能用len
    Traceback (most recent call last):
      File "<pyshell#8>", line 1, in <module>
        aa.sort(key=len)
    TypeError: object of type 'int' has no len()

    字符串情况: 默认ASCII表先后顺序排列

    >>> a = ['x11','abc323','e26','112ddd']
    >>> a.sort()       #默认按照ASCII表先后顺序排序
    >>> a
    ['112ddd', 'abc323', 'e26', 'x11']
    >>> a.sort(key=len)    # 默认第一原则 字符串从短到长排序,第二原则ASCII表先后顺序
    >>> a
    ['e26', 'x11', '112ddd', 'abc323']
    >>> a.sort(key=len,reverse=True)
    >>> a
    ['112ddd', 'abc323', 'e26', 'x11']

    注意: python3.0不允许不同数据类型进行排序 

    同时有数字和字符串的情况,不能排序:

    >>>a = ['x', 'y', 1, 2]
    >>> a.sort()
    Traceback (most recent call last):
      File "<pyshell#59>", line 1, in <module>
        a.sort()
    TypeError: unorderable types: str() < int()

    翻转:

        list.reverse()

    >>> a = ['x', 'y', 1, 2]
    >>> a.reverse()
    >>> a
    [2, 1, 'y', 'x']

    10. 获取下标  (list.index(elem))

        list.index(self,value,[start,[stop]])

         value: 带获取下标的元素

         start: 开始查询的下标

          stop:终止查询的下标

    >>> a = ['x', 'y', 1, 'x', 2, 'x']
    >>> a.index('x')
    0
    >>> a.index('x',1)
    3
    >>> a.index('x',4)
    5

    11. 拷贝 (list.copy())

     list.copy为浅拷贝,即只为列表元素的第一层开辟新地址,而第二层共用第一层的地址,也就是说,列表元素的第一层可以独立修改,而第二层不可独立修改,请看下面例子:

    >>>list_1 = ['x', 'y', 'z', [1, 2, 3]]  # 创建list_1
    >>>list_1_copy = list_1.copy()          # 拷贝list_1
    >>>list_1_copy[1] = 'Y'                 # 修改第一层元素的值
    >>>print(list_1, list_1_copy)           # 修改的第一层位置元素不同
    ['x', 'y', 'z', [1, 2, 3]] ['x', 'Y', 'z', [1, 2, 3]]
    >>>list_1_copy[-1][0] = '123'           # 修改第二层元素的值
    >>>print(list_1, list_1_copy)           # 修改的第二层位置元素相同
    ['x', 'y', 'z', ['123', 2, 3]] ['x', 'Y', 'z', ['123', 2, 3]]

    或者用copy模块的copy方法,同样是浅拷贝:

    import copy
    list_1 = ['x', 'y', 'z', [1, 2, 3]]  # 创建list_1
    list_2 = copy.copy(list_1)           # 浅拷贝
    list_1[1]= 'Y'                       # 改变第一层的值
    list_2[-1][-3] = '234'               # 改变第二层的值
    print(list_1, list_2)
    
    # 输出
    ['x', 'Y', 'z', ['234', 2, 3]] ['x', 'y', 'z', ['234', 2, 3]]

    深拷贝需要用deepcopy方法:

    import copy
    list_1 = ['x', 'y', 'z', [1, 2, 3]]  # 创建list_1
    list_3 = copy.deepcopy(list_1)       # 深拷贝
    list_1[2]= 'zz'
    list_3[-1][-3] = 888
    print(list_1, list_3)
    
    #输出,注意第二层的元素变化情况
    ['x', 'y', 'zz', [1, 2, 3]] ['x', 'y', 'z', [888, 2, 3]]

    二、元组(tuple)

    元组与列表相比要简单很多,因为元组一旦创建成功就不能修改,所以一般称为只读列表

    元组的创建与索引:

    >>> a = (1, 2, 'a')      # 注意此处的小括号
    >>> a
    (1, 2, 'a')
    >>> a[1]                    # 索引仍然用中括号
    2
    >>> a[1:]
    (2, 'a')

    tuple只有两个方法,count和index。

    >>> b = ('x', 'y', 1, 'x', 2, 'x')
    >>> b.index('x', 1)
    3
    >>> b.count('x')
    3
  • 相关阅读:
    科幻的意义---《超新星纪元》后记
    论文翻译第二弹--用python(或Markdown)对论文复制文本进行处理
    python note 001
    matlab读取txt文本
    VS中添加lib与dll
    Wake-Sleep(W-S)算法【转载】
    清华大学《C++语言程序设计进阶》线上课程笔记06---继承、派生、多态性
    清华大学《C++语言程序设计基础》线上课程笔记05---vector对象,对象的复制与移动,string类
    清华大学《C++语言程序设计基础》线上课程笔记04---指针
    Linux线程的信号量同步
  • 原文地址:https://www.cnblogs.com/tjuyuan/p/6718050.html
Copyright © 2011-2022 走看看