11.列表

数据容器

一种可以容纳多份数据的数据类型,容纳的每一份数据称之为1个元素,每一个元素,可以是任意类型的数据,如字符串、数字、布尔等。

Python有哪些数据容器:

  • list(列表)、tuple(元组)、str(字符串)、set(集合)、dict(字典)

list(列表)

列表内的每一个数据,称之为元素

  • 以 [ ] 作为标识
  • 列表内每一个元素之间,用逗号隔开

字面量: [元素1, 元素2, 元素3, ...]

定义变量: 变量名称 = [元素1, 元素2, 元素3, ...]

定义空列表:

  • 变量名称 = []
  • 变量名称 = list()
name_list = ['name1', 'name2', 'name3', 'name4', 'name5']
print(name_list)

my_list = ['name', 18, True]
print(my_list)
print(type(my_list))

# 嵌套列表的定义
my_list = [[1, 2, 3], [4, 5, "tang"]]
print(my_list)
['name1', 'name2', 'name3', 'name4', 'name5']
['name', 18, True]

[[1, 2, 3], [4, 5, 'tang']]

读取列表中的元素:

  • 列表的下标(索引):列表中的每一个元素,都有其位置的下标索引,从前向后的方向,从0开始,依次递增
  • 或者,可以反向索引,也就是从后向前,从 -1 开始,依次递减(-1、-2、-3、...)
  • 嵌套列表
  • 注意:通过下标索引取数据时,一定不要超出范围
# 查询列表中的内容
print(name_list[0])
print(name_list[1])
print("-----------------")
print(name_list[-1])
print(name_list[-3])

# 嵌套列表中的内容读取
print("-----------------")
print(my_list[0])
print(my_list[1])
print("-----------------")
print(my_list[0][1])
print(my_list[1][-1])
name1
name2
name5
name3
-----------------
[1, 2, 3]
[4, 5, 'tang']
-----------------
2
tang

list(列表)的常用操作

  • 插入元素
  • 删除元素
  • 清空列表
  • 修改元素
  • 统计元素个数

等等功能,这些功能称之为 列表的方法

函数是一个封装的代码单元,可以提供特定功能,在Python中,如果将函数定义为class(类)的成员,那么函数会称之为:方法

函数:

def add(x, y):

  return x + y

方法:

class Student:

  def add(self, x, y):

    return x + y

方法和函数功能一样,有传入参数,有返回值,只是方法的使用格式不同:

函数的使用:num = add(1, 2)

方法的使用: student = Student()

      num = student.add(1, 2)

  • 查找某元素的下标 功能:查找指定元素在列表的下标,如果找不到,报错ValueError

语法: 列表.index(元素) index就是列表对象(变量)内置的方法(函数)

print(name_list)
index = name_list.index("name2")
print(f"name2在列表中的下标索引值是:{index}")

# index = name_list.index("name6")   # ValueError: 'name6' is not in list
['name1', 'name2', 'name3', 'name4', 'name5']
name2在列表中的下标索引值是:1
  • 修改列表特定位置(索引)的值
name_list = ['name1', 'name2', 'name3', 'name4', 'name5']

name_list[1] = "tang2"
print(name_list)

name_list.insert(1, "tang3")
print(name_list)
['name1', 'tang2', 'name3', 'name4', 'name5']
['name1', 'tang3', 'tang2', 'name3', 'name4', 'name5']
  • 插入元素

语法:列表.index(下标, 元素),在指定的下标位置,插入指定的元素

name_list = ['name1', 'name2', 'name3', 'name4', 'name5']

name_list.insert(1, "tang")
print(name_list)
['name1', 'tang', 'name2', 'name3', 'name4', 'name5']
  • 追加元素

语法:列表append(元素),将指定元素追加到列表的尾部

name_list = ['name1', 'name2', 'name3', 'name4', 'name5']
name_list.append('name6')
print(name_list)
['name1', 'name2', 'name3', 'name4', 'name5', 'name6']
  • 追加元素-批量追加

语法:列表extend(其它数据容器),将其它数据容器的内容取出,依次追加到列表尾部

name_list = ['name1', 'name2', 'name3', 'name4', 'name5']
name_list.extend(['name6', 'name7', 'name8'])
print(name_list)
print('------------------------')
list2 = ['name9', 'name10']
name_list.extend(list2)
print(name_list)
['name1', 'name2', 'name3', 'name4', 'name5', 'name6', 'name7', 'name8']
['name1', 'name2', 'name3', 'name4', 'name5', 'name6', 'name7', 'name8', 'name9', 'name10']
  • 删除元素

语法1:del 列表[下标] 仅删除元素

语法2:列表.pop(下标) 不仅能删除元素,还能把元素取出作为返回值

name_list = ['name1', 'name2', 'name3', 'name4', 'name5']
del name_list[0]
print(name_list)
print('------------------------')
element = name_list.pop(2)
print(f"通过pop方法取出元素后列表内容:{name_list},取出的元素是:{element} ")
name_list.pop(1)
print(name_list)
['name2', 'name3', 'name4', 'name5']
通过pop方法取出元素后列表内容:['name2', 'name3', 'name5'],取出的元素是:name4
['name2', 'name5']
  • 删除某元素在列表中的第一个匹配项

语法:列表.remove(元素)

name_list = ['name1', 'name2', 'name3', 'name4', 'name5']
name_list.remove('name3')
print(name_list)
['name1', 'name2', 'name4', 'name5']
  • 清空列表

语法: 列表.clear()

name_list = ['name1', 'name2', 'name3', 'name4', 'name5']
name_list.clear()
print(name_list)
[]
  • 统计某元素在列表内的数量

语法:列表.count(元素)

name_list = ['name1', 'name2', 'name3', 'name4', 'name5']
count = name_list.count("name1")
print(count)
1
  • 统计列表中全部的元素数量

语法:len(列表)

name_list = ['name1', 'name2', 'name3', 'name4', 'name5']
len(name_list)
5

列表总结

  • 可能容纳多个元素(上限为2**63-1)
  • 可能容纳不同类型的元素(混装)
  • 数据是有序存储的(有下标序号)
  • 允许重复数据存在
  • 可以修改(增加或删除元素)

列表学习案例

my_list = [21, 25, 21, 23, 22, 20]

my_list.append(31)
print(my_list)

my_list.append([29, 33, 30])
print(my_list)

my_list.pop(0)
print(my_list)

my_list[-1].pop(-1)
print(my_list)

my_list[2] = 31
print(my_list)

del my_list[-1][0]
print(my_list)

my_list.index(31)
print(my_list.index(31))
[21, 25, 21, 23, 22, 20, 31]
[21, 25, 21, 23, 22, 20, 31, [29, 33, 30]]
[25, 21, 23, 22, 20, 31, [29, 33, 30]]
[25, 21, 23, 22, 20, 31, [29, 33]]
[25, 21, 31, 22, 20, 31, [29, 33]]
[25, 21, 31, 22, 20, 31, [33]]
2

列表的遍历-while循环

将容器内的元素依次取出进行处理的行为,称之为:遍历、迭代


def list_while_func():
    """
    使用while循环遍历列表的演示函数
    :return: None
    循环控制的变量通过下标索引来控制,默认0
    每一次循环将下标索变量+1
    循环条件:下标索引变量 < 列表的元素数量
    """
    my_list = ['name1', 'name2', 'name3', 'name4', 'name5']
    index = 0
    while index < len(my_list):
        print(my_list[index])
        index += 1
list_while_func()
name1
name2
name3
name4
name5

列表的遍历-for循环

def list_for_func():
    my_list = [21, 25, 21, 23, 22, 20]
    sum = 0
    for i in my_list:
        print(i)
        sum = sum + i
    print(sum)

list_for_func()
21
25
21
23
22
20
132

列表的遍历-while与for循环对比

for循环更简单,while更灵活

  • 在循环控制上:

  while循环可以自定循环条件,并自行控制

  for循环不可以自定循环条件,只可以一个个从容器内取出数据

  • 在无限循环上:

  while循环可以通过条件控制做到无限循环

  for循环理论上不可以,因为被遍历的容器容量不是无限的

  • 在使用场景:

  while循环适用于任何想要循环的场景

  for循环适用于,遍历数据容器的场景或简单的固定次数循环场景

列表的遍历-案例

定义一个列表,内容是:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

  • 遍历列表,取出列表内的偶数,并存入一个新的列表对象中
  • 使用while循环和for循环各操作一次
# while循环
def list_while():
    my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    new_list = []
    index = 0
    while index < len(my_list):
        print(my_list[index])
        if my_list[index] % 2 == 0:
            new_list.append(my_list[index])
            index += 1
        else:
            index += 1
    print(new_list)
list_while()
1
2
3
4
5
6
7
8
9
10
[2, 4, 6, 8, 10]
# for循环
def list_for():
    my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    new_list = []
    for i in my_list:
        print(i)
        if i % 2 == 0:
            new_list.append(i)
    print(new_list)
list_for()
1
2
3
4
5
6
7
8
9
10
[2, 4, 6, 8, 10]