zoukankan      html  css  js  c++  java
  • 列表操作

    一、列表基础

    列表是序列中的一种,所以所有序列的属性或者方法都适用于列表,而序列就是使用一对中括号将序列中的元素值括起来。

    1、创建列表

    列表是可迭代对象,能够进行for循环,创建形式也是多样的。

    #直接通过[]进行创建
    l= [1,"hello",[4,5],{"name":"zhangsan"}]
    #关键字list进行创建
    l2 = list([1,23,3])
    l3 = [1,23,["shen","jianping"],43,566,77]
    print(l2) #[1, 23, 3]
    print(type(l2))#<class 'list'>

    2、索引

    列表中的所有元素都是有编号的,编号是从0开始递增,这个编号就是列表元素的索引,所有的元素都可以通过索引访问。

    l=['zhangsan','lisi','wangwu']
    print(l[0])#zhangsan
    print(l[2])#wangwu

    列表的索引和字符串的索引是一样的,也可以通过负数取值,-1代表最后一个,依次类推。

    l=['zhangsan','lisi','wangwu']
    print(l[-1])#wangwu
    print(l[-2])#lisi

    3、分片

     分片是从列表A中获取一个子列表B,从A中获取B,需要指定B在A中的开始索引以及结束索引,因此,分片操作需要指定两个索引。

    l=[1,2,3,4,5,6,7]
    print(l[2:5])#[3, 4, 5]
    print(l[-4:-2])#[4, 5]

    使用负数作为开始索引,并省略结束索引

    l=[1,2,3,4,5,6,7]
    print(l[-3:])#[5, 6, 7]
    print(l[-3:7])#[5, 6, 7] 结尾使用了正整数作为索引

    省略开始索引

    l=[1,2,3,4,5,6,7]
    print(l[:3])#[1, 2, 3] 获取前三个值的列表

    设置步长

    对列表进行分片时,默认的步长是1,即获取相邻的元素,如果获取非相邻元素,就需要指定步长了。

    l=[1,2,3,4,5,6,7]
    print(l[:3:2])#[1, 3]

    步长可以是负数,但不可以为0,如果为负数,分片会从列表的右侧开始,所以开始的索引要大于结束的索引。

    l=[1,2,3,4,5,6,7,8,9]
    print(l[7:2:-2])#[8, 6, 4]

    注意:

    • 分片取值左取右不取,如果步长为负数,则相反。

    4、列表相加

    列表的相加是收尾相连,并不是元素的相加。

    l1=[1,2,3,4,5,6,7,8,9]
    l2=['h','e','l','l','0']
    print(l1+l2)#[1, 2, 3, 4, 5, 6, 7, 8, 9, 'h', 'e', 'l', 'l', '0']

    注意:列表不能和字符串这样不同类型的数据进行相加。

    5、列表的乘法

    l=[1,2,3,4,5,6,7,8,9]
    print(l*2)#[1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9]

    6、检查某个值是否属于列表

    使用in进行判断

    l=[1,2,3,4,5,6,7,8,9]
    print(2 in l)#True

    7、列表长度、最大值、最小值

    这是三个内建函数,len()、max()、min(),用于返回列表中元素的数量、最大的元素、最小的元素。注意使用min()和max()方法时,列表中的每个元素必须是可比较。

    values=[1,2,3,4,5,6,7,8,9]
    print(len(values))#9
    print(max(values))#9
    print(min(values))#1

    二、列表的基本操作

    1、列表元素赋值

     之前使用列表索引获取列表中的某个值,而修改列表中的某一个元素,使用一对中括号指定元素在列表中的索引,然后使用赋值运算符(“=”)进行赋值。

    l=["hello","world"]
    l[1]="bright"
    print(l)#['hello', 'bright']

    2、删除列表元素

    使用del进行删除

    l=["hello","world"]
    del l[1]
    print(l)#['hello']

    3、分片赋值

    分片赋值是将列表的某一部分通过分片获取,然后将其替换

    l=["a","b","c","d","e"]
    l[2:]=[1,2,3]
    print(l)#['a', 'b', 1, 2, 3]

    利用这个特性可以在一个列表中插入一些元素或者删除一些元素

    l=["a","b","c","d","e"]
    #插入元素
    l[1:1]=[1,2,3,4,5]#['a', 1, 2, 3, 4, 5, 'b', 'c', 'd', 'e']
    print(l)
    #删除元素
    l[1:3]=[]
    print(l)#['a', 3, 4, 5, 'b', 'c', 'd', 'e']

    三、列表方法

    在列表中有以下一些方法:

    class list(object):
        """
        list() -> new empty list
        list(iterable) -> new list initialized from iterable's items
        """
        def append(self, p_object): # real signature unknown; restored from __doc__
            """ L.append(object) -> None -- append object to end """
            pass
    
        def clear(self): # real signature unknown; restored from __doc__
            """ L.clear() -> None -- remove all items from L """
            pass
    
        def copy(self): # real signature unknown; restored from __doc__
            """ L.copy() -> list -- a shallow copy of L """
            return []
    
        def count(self, value): # real signature unknown; restored from __doc__
            """ L.count(value) -> integer -- return number of occurrences of value """
            return 0
    
        def extend(self, iterable): # real signature unknown; restored from __doc__
            """ L.extend(iterable) -> None -- extend list by appending elements from the iterable """
            pass
    
        def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
            """
            L.index(value, [start, [stop]]) -> integer -- return first index of value.
            Raises ValueError if the value is not present.
            """
            return 0
    
        def insert(self, index, p_object): # real signature unknown; restored from __doc__
            """ L.insert(index, object) -- insert object before index """
            pass
    
        def pop(self, index=None): # real signature unknown; restored from __doc__
            """
            L.pop([index]) -> item -- remove and return item at index (default last).
            Raises IndexError if list is empty or index is out of range.
            """
            pass
    
        def remove(self, value): # real signature unknown; restored from __doc__
            """
            L.remove(value) -> None -- remove first occurrence of value.
            Raises ValueError if the value is not present.
            """
            pass
    
        def reverse(self): # real signature unknown; restored from __doc__
            """ L.reverse() -- reverse *IN PLACE* """
            pass
    
        def sort(self, key=None, reverse=False): # real signature unknown; restored from __doc__
            """ L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE* """
            pass
    list类
    • append 在列表最后插入新的值
    • clear 清除列表的内容
    • copy 用于复制一个列表
    • count 统计某个元素在列表中出现的次数
    • extend 在原列表后扩展新的列表
    • index 从列表中找出某个值第一次出项的索引值
    • insert 用于将值插入都列表指定的位置
    • pop 用于移除列表中的元素(默认移除列表最后一个元素),并返回该元素的值
    • remove 用于移除列表中某个元素的的第一次匹配项
    • reverse 用于将列表中的元素反向存放
    • sort 用于对列表进行排序,调用该方法会改变原来的列表

    1、append()

    l=[1,2,3]
    l.append(4) #添加单个元素
    print(l) #[1, 2, 3, 4]
    l=[1,2,3]
    l.append([4,5])#添加列表
    print(l) #[1, 2, 3, [4, 5]]

    2、clear()

    l=[1,2,3]
    l.clear()
    print(l)#[]

    3、copy()

    copy后就是一个新的对象,与之前的就没有关系,修改新的列表,不会影响之前的列表。

    l1=[1,2,3]
    print(id(l1))#90554760
    l2=l1.copy()
    print(id(l2))#85322120
    l3=l1
    print(id(l3))#90554760

    4、count()

    l=['a','b','c','a','d','a']
    print(l.count('a'))#3

    5、extend()

    l1=[1,2,3]
    l2=[4,5,6]
    l1.extend(l2)
    print(l1) #[1, 2, 3, 4, 5, 6]

    使用列表连接以及分片也是可以达到这种效果的,但是效率没有这个高。

    #列表连接
    l1=[1,2,3]
    l2=[4,5,6]
    print(l1+l2)#[1, 2, 3, 4, 5, 6]
    
    #切片
    l1=[1,2,3]
    l2=[4,5,6]
    l1[len(l1):]=l2
    print(l1)#[1, 2, 3, 4, 5, 6]

    6、index()

    l=['a','b','c','a','d']
    print(l.index('a'))#0

    如果元素不在列表中就会抛出异常

    l=['a','b','c','a','d']
    print(l.index('e'))
    
    ---------------------------------------------------------------------------
    ValueError                                Traceback (most recent call last)
    <ipython-input-11-862cf3f75961> in <module>
          1 l=['a','b','c','a','d']
          2 print(l.index('a'))#0
    ----> 3 print(l.index('e'))
    
    ValueError: 'e' is not in list

    7、insert()

    l=['a','b','c','a','d']
    #在索引为2的地方插入值
    l.insert(2,[4,5,6])#['a', 'b', [4, 5, 6], 'c', 'a', 'd']
    print(l)

    同样也可以使用分片赋值

    l=['a','b','c','a','d']
    l[2:2]=[[4,5,6]]
    print(l)#['a', 'b', [4, 5, 6], 'c', 'a', 'd']

    8、pop()

    l=['a','b','c','a','d']
    result=l.pop()
    result1=l.pop(1)
    print(result)#d 返回默认删除的最后一个元素
    print(result1)# 返回指定的删除元素
    print(l)#['a', 'b', 'c', 'a']

    9、remove()

    l=['a','b','c']
    result=l.remove('a')
    #不会返回删除的元素
    print(result)#None
    
    print(l)#['b', 'c']

    remove中删除不存在的元素会抛出异常

    10、reverse()

    l=[1,2,3,4,5,6]
    #将列表元素倒序排放
    l.reverse()
    print(l)#[6, 5, 4, 3, 2, 1]

    11、sort()

    l=[1,4,3,6,7,2]
    #对列表进行升序排列(默认方式)
    l.sort()
    print(l)#[1, 2, 3, 4, 6, 7]
    
    
    l=[1,4,3,6,7,2]
    #对列表进行降序排列,与reverse方法效果一样
    l.sort(reverse=True)
    print(l)#[7, 6, 4, 3, 2, 1]

    使用sort排序会直接修改原列表,如果想修改其副本,可以使用以下方法:

    • 分片操作
    l=[1,4,3,6,7,2]
    l1=l[:]
    l1.sort()
    print(l)#[1, 4, 3, 6, 7, 2]
    print(l1)#[1, 2, 3, 4, 6, 7]
    • sorted函数
    l=[1,4,3,6,7,2]
    l1=sorted(l)
    print(l)#[1, 4, 3, 6, 7, 2]
    print(l1)#[1, 2, 3, 4, 6, 7]

    四、其它方法

    1、enumerate

    class enumerate(object):
        """
        enumerate(iterable[, start]) -> iterator for index, value of iterable
        
        Return an enumerate object.  iterable must be another object that supports
        iteration.  The enumerate object yields pairs containing a count (from
        start, which defaults to zero) and a value yielded by the iterable argument.
        enumerate is useful for obtaining an indexed list:
            (0, seq[0]), (1, seq[1]), (2, seq[2]), ...
        """
        def __getattribute__(self, *args, **kwargs): # real signature unknown
            """ Return getattr(self, name). """
            pass
    
        def __init__(self, iterable, start=0): # known special case of enumerate.__init__
            """ Initialize self.  See help(type(self)) for accurate signature. """
            pass
    
        def __iter__(self, *args, **kwargs): # real signature unknown
            """ Implement iter(self). """
            pass
    
        @staticmethod # known case of __new__
        def __new__(*args, **kwargs): # real signature unknown
            """ Create and return a new object.  See help(type) for accurate signature. """
            pass
    
        def __next__(self, *args, **kwargs): # real signature unknown
            """ Implement next(self). """
            pass
    
        def __reduce__(self, *args, **kwargs): # real signature unknown
            """ Return state information for pickling. """
            pass
    enumerate类
    l= [1,"hello",[4,5],{"name":"bright"}]
    for i,j in enumerate(l):
        print(i,j)
    -----------------------------------------------------输出索引和值----------------------------
    0 1
    1 hello
    2 [4, 5]
    3 {'name': 'bright'}
  • 相关阅读:
    那些离不开的 Chrome 扩展插件
    Spring Boot 实战 —— 入门
    Maven 学习笔记
    Linux lvm 分区知识笔记
    Linux 双向 SSH 免密登录
    CentOS Yum 源搭建
    Ubuntu 系统学习
    iOS 测试三方 KIF 的那些事
    Swift 网络请求数据与解析
    iOS Plist 文件的 增 删 改
  • 原文地址:https://www.cnblogs.com/shenjianping/p/10997497.html
Copyright © 2011-2022 走看看