当前位置 博文首页 > RunningOnMyWay的博客:Python3基础学习----数组列表list

    RunningOnMyWay的博客:Python3基础学习----数组列表list

    作者:[db:作者] 时间:2021-06-23 15:08

    1.列表创建
    >>> lis = [1,2,3]
    
    2.列表尾部添加元素
    >>> lis.append(4)
    >>> lis
    [1, 2, 3, 4]
    
    3.列表插入元素

    insert(0,4) 第一个参数为数组索引位置,即在该位置插入元素

    >>> lis.insert(0,4)
    >>> lis
    [4, 1, 2, 3]
    
    4.扩展列表,可用于合并列表

    新定义lis2,执行extend之后,lis2没有改变,而lis中多了lis2的元素

    >>> lis2=["a","b"]
    >>> lis.extend(lis2)
    >>> lis
    [4, 1, 2, 3, 'a', 'b']
    >>> lis2
    ['a', 'b']
    
    5.删除结尾或指定索引的元素

    lis.pop()与lis.pop(-1)等效,0正数从左边开始,负数从右边开始索引位置

    >>> lis.pop()
    'b'
    >>> lis
    [4, 1, 2, 3, 'a']
    >>> lis.pop(0)
    4
    >>> lis
    [1, 2, 3, 'a']
    >>> 
    
    6.删除指定元素

    在使用remove时默认只会删除第一个相同元素

    >>> lis.append(2)
    >>> lis
    [1, 2, 3, 'a', 2]
    >>> lis.remove(2)
    >>> lis
    [1, 3, 'a', 2]
    >>> 
    
    7.清空数组

    使用clear方法清空了数组中的元素,而第二种新建了一个数组

    >>> lis2.clear()
    >>> lis2
    []
    >>> lis2=["a","b"]
    >>> lis2=[]
    >>> lis2
    []
    >>> 
    
    8. 数组排序

    当元素不是同种类型时排序执行时会报错,使用sort排序,使用reverse实现当前元素的反序; 使用sorted实现排序,会新生成一个数组,而不会改变原有数组;

    >>> lis2=["b","c","a"]
    >>> lis.sort()
    Traceback (most recent call last):
      File "<pyshell#31>", line 1, in <module>
        lis.sort()
    TypeError: '<' not supported between instances of 'str' and 'int'
    >>> lis
    [1, 3, 'a', 2]
    >>> lis2.sort()
    >>> lis2
    ['a', 'b', 'c']
    >>> lis2.reverse()
    >>> lis2
    ['c', 'b', 'a']
    >>> sorted(lis2)
    ['a', 'b', 'c']
    >>> lis2
    ['c', 'b', 'a']
    >>> 
    
    9.列表与字符串的互相转化

    字符串转化为列表直接使用list方法,而将列表转为字符串时使用字符串的方法join,list是没有这个方法的;join之后返回一个字符串

    >>> str1 = "abcdefd"
    >>> str1
    'abcdefd'
    >>> lis2 = list(str1)
    >>> lis2
    ['a', 'b', 'c', 'd', 'e', 'f', 'd']
    >>> "".join(lis2)
    'abcdefd'
    >>> lis2
    ['a', 'b', 'c', 'd', 'e', 'f', 'd']
    >>> "-".join(lis2)
    'a-b-c-d-e-f-d'
    >>> lis2.join("")
    Traceback (most recent call last):
      File "<pyshell#44>", line 1, in <module>
        lis2.join("")
    AttributeError: 'list' object has no attribute 'join'
    
    10.查看方法的帮助文档
    >>> help(str.join)
    Help on method_descriptor:
    
    join(self, iterable, /)
        Concatenate any number of strings.
        
        The string whose method is called is inserted in between each given string.
        The result is returned as a new string.
        
        Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
    
    >>> help(list.append)
    Help on method_descriptor:
    
    append(self, object, /)
        Append object to the end of the list.
    
    >>> 
    
    11.查看当前对象有哪些方法
    >>> dir(list)
    ['__add__', '__class__', '__contains__',..这里我手动省略..]
    >>> dir(str)
    ['__add__', '__class__',..这里我手动省略..]
    >>>