1.描述

  • 表现形式:在Python中list使用中括号 [] 来表示
  • 含义:列表是由一系列按照特定顺序排列的元素组成

    2.访问list

    使用索引来进行访问:print(list_1[4])访问第五个元素,这个访问就是去掉了中括号以及引号,让输出结果干净整洁

    3.增加元素

    3.1.append():

    在末尾添加元素,不影响其它元素的值
    1. list_1 = ['yellow', 'red', 'blue']
    2. list_2 = ['hello', 'hi']
    3. list_1.append(111)
    4. print(list_1)
    5. '''输出结果:['yellow', 'red', 'blue', 111]'''

    3.2.insert():

    使用索引在指定位置添加元素
    1. list_1 = ['yellow', 'red', 'blue']
    2. list_2 = ['hello', 'hi']
    3. list_1.insert(0,'sky')
    4. print(list_1)
    5. '''输出结果:['sky','yellow', 'red']

    3.3.extend():

    合并拼接两个list(被拼接的在后面显示)
    1. list_1 = ['yellow', 'red', 'blue']
    2. list_2 = ['hello', 'hi']
    3. list_1.extend(list_2)
    4. print(list_1)
    5. '''输出结果:[ 'yellow', 'red', 'blue', 'hello', 'hi']'''

    4.删除元素

    4.1.pop():

    删除末尾元素,或者使用索引删除指定位置元素,可返回删除值,可以继续使用他
    1. list_1 = ['yellow', 'red', 'blue']
    2. list_2 = ['hello', 'hi']
    3. list_1.pop()
    4. print(list_1)
    5. '''输出结果:['yellow', 'red']'''

    4.2.del:

    使用索引删除指定位置的元素值
    1. list_1 = ['yellow', 'red', 'blue']
    2. list_2 = ['hello', 'hi']
    3. del list_1[0]
    4. print(list_1)
    5. '''输出结果:['red', 'blue']'''

    4.3.remove():

    如果只知道需要删除元素的值,而不知道其索引的位置,可使用(只删除第一个指定的值,如果要删除的值在列表当中多次出现,则需要使用循环来判断是否删除了所有的值)
    1. list_1 = ['yellow', 'red', 'blue']
    2. list_2 = ['hello', 'hi']
    3. list_1.remove('yellow')
    4. print(list_1)
    5. '''输出结果:['red', 'blue']'''

    5.修改元素

    在修改list中的值的时候,需要明确被修改值得索引
    1. list_1 = ['yellow', 'red', 'blue']
    2. list_2 = ['hello', 'hi']
    3. list_1[0] = 'hello'
    4. print(list_1)
    5. '''输出结果:['hello', 'red', 'blue']'''

    6.组织列表

    6.1.sort():

    永久性的更改列表的排列顺序:按照字母先后排列
    1. list_1 = ['yellow', 'red', 'blue']
    2. list_1.sort()
    3. print(list_1)
    4. '''输出结果:['blue', 'red', 'yellow']'''

    6.2.sort(reverse=true):

    永久性的更改list排列循序:字母的反方向进行排列
    1. list_1 = ['yellow', 'red', 'blue']
    2. list_1.sort(reverse=True)
    3. print(list)
    4. '''输出结果:['yellow', 'red', 'blue']'''

    6.3.sorted:

    是list临时排列,不改变原来的循序
    1. list_1 = ['yellow', 'red', 'blue']
    2. print(sorted(list_1))
    3. '''输出结果:['blue', 'red', 'yellow']'''
    4. print(list_1)
    5. '''输出结果:['yellow', 'red', 'blue'],此为原来的list顺序'''

    6.4.reverse():

    倒着打印list,reverse()不是指按照字母相反的循序进行打印,而是反转list的排列顺序
    1. list_1 = ['yellow', 'red', 'apple','blue']
    2. list_1.reverse()
    3. print(list_1)
    4. '''输出结果为:['blue', 'apple', 'red', 'yellow']'''

    6.5.len():

    确定list的长度,比如确定网站有多少注册用户等等
    1. list_1 = ['yellow', 'red', 'apple','blue']
    2. print(len(list_1))
    3. '''输出结果:4'''

    总结

    python_list - 图1