python——列表
1. 创建列表
通过内置函数list()创建列表
list = [] # 中括号方式创建列表
list= list(rangge(1, 10, 2)) # list() 函数创建列表
2. 增加元素
append()在列表尾部追加一个元素,注意该方法可以接受单个值,也可以接受元组或列表,但是此时,元组或列表是作为一个整体追加的,这样形成了嵌套insert()在列表的指定位置插入extend()将一个列表的元素到列表的尾部
list1 = [1, 2, 3] # 创建一个列表
a = list1.append([4, 5, 6]) # append追加一个列表
print(list1)
b = list1.extend([4, 5, 6]) # extend将列表里每个元素追加到列表尾部
print(list1)
c = list1.insert(1, 9) #insert 在指定索引位置插入一个元素
print(list1)
输出
[1, 2, 3, [4, 5, 6]]
[1, 2, 3, [4, 5, 6], 4, 5, 6]
[1, 9, 2, 3, [4, 5, 6], 4, 5, 6]
3. 删除元素
del()根据索引删除列表中的一个元素或一段区间中的元素remove()根据元素本身删除列表中的某个元素(第一个)clear()清空列表中所有的元素
list2 = [1, 2, 9, 4, 5, 2, 4, 6]
list2.remove(9) # 删除指定元素
print(list2)
del list2[0:3] # 删除区间元素
print(list2)
输出
[1, 2, 4, 5, 2, 4, 6]
[5, 2, 4, 6]
4. 置逆和排序
reverse()将列表中的元素置逆sort()将列表中的元素排序(默认从小到大,如果从大到小,需要添加参数 reverse = True)
list1 = [1, 3, 5, 2, 4, 6]
list1.reverse()
print(list1)
list1.sort(reverse = True)
print(list1)
输出
[6, 4, 2, 5, 3, 1]
[6, 5, 4, 3, 2, 1]
5. 弹出元素
pop()将列表作为栈,实现出栈操作(入栈用append方法)
list1 = [1, 3, 5, 2, 4, 6]
list1.pop()
print(list1)
输出
[1, 3, 5, 2, 4]
6. 浅拷贝和深拷贝
浅拷贝方式
list.copy()copy.copy()
# 列表只有不可变序列数据向
list1 = [1, 2, 3]
list2 = list1.copy()
list2[1] = 5
print(list1)
print(list2)
输出
[1, 2, 3]
[1, 5, 3]
# 列表中有列表等可变序列
list1 = [1, 2, 3,[7, 8, 9]]
list2 = list1.copy() # 复制list1
# list2 = copy.copy(list1) # 需要import copy模块
list2[3][0] = 5
list2[1] = 6
print(list1)
print(list2)
输出
[1, 2, 3, [5, 8, 9]]
[1, 6, 3, [5, 8, 9]]

深拷贝方式
copy.deepcopy
import copy
list1 = [1, 2, 3,[7, 8, 9]]
list2 = copy.deepcopy(list1)
list2[3][0] = 5
print(list1)
print(list2)
输出
[1, 2, 3, [7, 8, 9]]
[1, 2, 3, [5, 8, 9]]

变量赋值方式(list2 = list1)
list1 = [1, 2, 3,[7, 8, 9]]
list2 = list1
list2[3][0] = 5
list2[1] = 6
print(list1)
print(list2)
输出
[1, 6, 3, [5, 8, 9]]
[1, 6, 3, [5, 8, 9]]
结果显示list2 的所有修改都有影响了list1
本文来自博客园,作者:hcypeu,转载请注明原文链接:https://www.cnblogs.com/hcypeu/p/16475224.html


浙公网安备 33010602011771号