8、Python列表

作者: 魔方宫殿 | 来源:发表于2022-03-22 22:29 被阅读0次
    Life is short, you need Python!

    上集回顾:

    1. Python函数
    2. while循环嵌套

    Python列表(list)是一种有序的集合,是 Python 中使用最频繁的数据类型。列表可以完成大多数集合类的数据结构实现,可以随时添加和删除其中的元素。列表中元素的类型同城相同,也可以不相同,它支持数字,字符串甚至可以包含列表(所谓嵌套)。列表(list)是写在方括号 [] 之间、用逗号分隔开的元素列表。

    >>> listA = ['a', 'b', 'c']
    >>> listA
    ['a', 'b', 'c']
    >>> listB = [1, 2, 3, 4, 5]
    >>> listB
    [1, 2, 3, 4, 5]
    >>> listC = [1, 'a', 2, 'b', 3.1, 'c']
    >>> listC
    [1, 'a', 2, 'b', 3.1, 'c']
    >>> listD = [1, 'a', [1, 2, 3], 'b']
    >>> listD
    [1, 'a', [1, 2, 3], 'b']
    

    列表元素个数可以通过函数len()获得:

    >>> len(listD)
    4
    

    和字符串一样,列表同样可以被索引和截取,列表被截取后返回一个包含所需元素的新列表。


    列表索引
    >>> t = ['a', 'b', 'c', 'd', 'e']
    >>> t[2]
    'c'
    >>> t[-3]
    'c'
    >>> t[1:3]
    ['b', 'c']
    >>> t[-4:-2]
    ['b', 'c']
    >>> t
    ['a', 'b', 'c', 'd', 'e']
    

    当索引超出了范围时,Python会报一个IndexError错误,所以,要确保索引不要越界,记得最后一个元素的索引是len(t) - 1。

    >>> t[4]
    'e'
    >>> t[5]
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    IndexError: list index out of range
    

    list是一个可变的有序表,可以用append(item)追加元素到list末尾:

    >>> t.append('f')
    >>> t
    ['a', 'b', 'c', 'd', 'e', 'f']
    

    可以用insert(position, item)把元素插入到指定位置,比如把字母'g'插入到正中间:

    >>> t.insert(3, 'g')
    >>> t
    ['a', 'b', 'c', 'g', 'd', 'e', 'f']
    

    函数pop()会删除列表末尾的元素:

    >>> t
    ['a', 'b', 'c', 'g', 'd', 'e', 'f']
    >>> t.pop()
    'f'
    >>> t
    ['a', 'b', 'c', 'g', 'd', 'e']
    

    也可以用pop(position)删除指定位置的元素,比如删除insert进去的'g':

    >>> t.pop(3)
    'g'
    >>> t
    ['a', 'b', 'c', 'd', 'e']
    

    想修改或替换某个元素,可以直接赋值给对应的索引位置:

    >>> t[2] = 'p'
    >>> t
    ['a', 'b', 'p', 'd', 'e']
    

    函数sort()可以对列表进行排序,排序会改变原列表的内容:

    l = [5, 4, 3, 2, 1]
    >>> l.sort()
    >>> l
    [1, 2, 3, 4, 5]
    

    本集技能总结:
    Python列表:list

    1. 用[]表示,元素用逗号分隔;
    2. 列表长度:len()
    3. 索引和范围,小心越界;
    4. 追加元素:append(item);
    5. 插入元素:insert(position, item);
    6. 删除末尾元素: pop();
    7. 删除指定位置的元素: pop(position);
    8. 列表排序: sort()。

    下集见

    相关文章

      网友评论

        本文标题:8、Python列表

        本文链接:https://www.haomeiwen.com/subject/jdpddrtx.html