列表
作用:多个装备,多个爱好,多门课程等
定义:[]内可以有多个任意类型的值,逗号分隔
province_name_list = [‘北京‘,‘上海‘,‘天津‘,‘广州‘,‘深圳‘] province_name_list1 = list([‘北京‘,‘shanghai‘,‘天津‘,5,‘深圳‘]) print(province_name_list) # [‘北京‘, ‘上海‘, ‘天津‘, ‘广州‘, ‘深圳‘] print(province_name_list1) # [‘北京‘, ‘shanghai‘, ‘天津‘, 5, ‘深圳‘]
需要掌握
# 1. 按索引存取值(正向存取+反向存取):即可存也可以取
l = [1,2,3,4] print(l[0:4:1]) # [1, 2, 3, 4] print(l[0::]) # [1, 2, 3, 4] print(l[5::-1]) # [4, 3, 2, 1] print(id(l)) # 4508301640 l[0] = 69 print(id(l)) # 4508301640 print(l) # [69, 2, 3, 4]
# 2. 切片(顾头不顾尾,步长)
province_name_list = [‘北京‘,‘上海‘,‘天津‘,‘广州‘,‘深圳‘] print(province_name_list[1:4]) # [‘上海‘, ‘天津‘, ‘广州‘] print(province_name_list[-2:]) # [‘广州‘, ‘深圳‘]
# 3. 长度
l = [11,22,33,44,55] print(len(l)) >>> 5
# 4. 成员运算in和not in
l = [11,22,33,44,55] print( 444 in l) >>> False
# 5. 往列表中添加元素(#重点#)
append
## 尾部添加一个66 l = [11,22,33,44,55] l.append(66) print(l) >>> [11, 22, 33, 44, 55, 66]
insert
## 任意位置添加元素 l = [11,22,33,44,55] l.insert(2,96) # 通过索引在任意位置添加元素 print(l) # 注意insert值能将被添加的数据当作列表的一个元素 >>> [11, 22, 96, 33, 44, 55]
extend
## 添加容器类型数据 l = [11,22,33,44,55] l1 = [99,88,77,66] l.append(l1) l.insert(-1,l1) l.extend(l1) # 内部原理for循环l1一个个追加到列表的尾部 l.extend([1,]) print(l) >>> [11, 22, 33, 44, 55, [99, 88, 77, 66], [99, 88, 77, 66], 99, 88, 77, 66, 1]
# 6. 删除
# dell = [11,22,33,44,55] print(l) # [11, 22, 33, 44, 55] del l[2] # del适用于所有的删除操作 print(l) # [11, 22, 44, 55]
# pop l = [11,22,33,44,55 res1 = l.pop() # 尾部弹出 res2 = l.pop() res3 = l.pop() print(res1,res2,res3) # 55 44 33 l = [11,22,33,44,55] res1 = l.pop(0) # 可以指定索引 按照索引弹出元素 print(res1) # 11
#remove l = [11,22,33,44,55] res = l.remove(33) # 指定要删除的元素的值 print(l) # [11, 22, 44, 55] print(res) # None
# 7. 循环
l = [11,22,33,44,55] for i in l: print(i) >>> 11 22 33 44 55
原文地址:https://www.cnblogs.com/PowerTips/p/11129662.html
时间: 2024-11-09 05:58:04