一.了解列表
在 Python 中,列表(List)是一种有序、可变的数据结构,可以存储多个不同类型的元素。列表的定义方式非常简单,使用方括号[] 来包裹元素,元素之间用逗号 ,
分隔:
# 定义一个空列表
empty_list = []
# 定义包含整数的列表
numbers = [1, 2, 3, 4, 5]
# 定义包含不同数据类型的列表
mixed_list = [10, "hello", 3.14, True, None]
# 定义嵌套列表(列表中包含列表)
nested_list = [1, [2, 3], [4, [5, 6]]]
二.列表的查询
students = ['张三','李四','王五','赵六']
#同day2中字符串的查询一样
print(students[1]) #将得到李四
print(students[-1]) #将得到赵六
print(students[0:2]) #同样左闭右开,将得到列表形式的['张三','李四']
print(students[::2]) #步长为2
三.列表的添加/拼接
1.append()方法
students = ['张三','李四','王五','赵六']
#append() 在列表的末尾添加数据
students.append('钱七')
print(students)
2.insert()方法
#insert() 在指定位置插入内容
students.insert(1,'李华')
print(students)
3.extend()方法
将一个列表的元素添加到另一个列表的末尾(修改原列表,无返回值)
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2) # 将 list2 的元素添加到 list1 中
print(list1) # 输出: [1, 2, 3, 4, 5, 6]
print(list2) # 输出: [4, 5, 6](list2 不变)
4.+运算符
直接将两个列表相加,返回一个新的合并列表。注意参与拼接的对象类型必须一致(都为列表、都为字符串或都为元组等),否则会报错。
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined = list1 + list2
print(combined) # 输出: [1, 2, 3, 4, 5, 6]
print(list1) # 输出: [1, 2, 3](原列表不变)
5.切片赋值
不仅能追加到末尾,还能插入到列表的任意位置
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1[len(list1):] = list2 # 等价于 extend()
print(list1) # 输出: [1, 2, 3, 4, 5, 6]
# 插入到指定位置(如索引1)
list1 = [1, 2, 3]
list1[1:1] = list2
print(list1) # 输出: [1, 4, 5, 6, 2, 3]
四.列表的修改
students[2] = '唐八'
print(students)
五.列表的删除
1.del语句
可以根据索引删除指定元素,也可以删除整个列表或列表的切片
# 删除索引为2的元素(30)
del students[2]
print(students)
# 删除从索引1到3的元素(不包含3)
del students[1:3]
print(students)
# 删除整个列表
del students
2.pop()方法
根据索引删除元素并返回该元素(默认删除最后一个元素):
#students.pop() 默认删除最后一个,也可指定删除某个位置的
students.pop()
print(students)
students.pop(2)
print(students)
3.remove()方法
#remove('xx') 就是删掉了xx
students.remove('王五')
print(students)