列表
1 列表的初识
- 为什么需要列表?
- 字符串只能存储少量的数据
- 存储数据类型单一
- 什么是列表?
- 可以存储任意数据类型,每隔元素以逗号隔开
- python常用的容器型数据类型,list (列表)
- 列表是有序的
- 32位的python限制是536870912 个元素
- 64位python的限制是 1152921504606846975 个元素
2 索引 切片 步长
- 索引
data_list = [1,2,"美",True,["a","g"]]
#索引
print(data_list[0],type(data_list[0]))
#运行结果
1 <class 'int'>
#根据索引取出的值类型保持原有类型
- 切片
data_list = [1,2,"美",True,["a","g"]]
#索引
# print(data_list[0],type(data_list[0]))
#切片
print(data_list[:2])
print(data_list[3:6])
print(data_list[1:6:2])
#运行结果
[1, 2]
[True, ['a', 'g']]
[2, True]
3 列表的增删改查
- 列表的创建
#方式一
list_1 = [1,2,"god"]
#方式二
# l2_list = list()
l2_list = list("afsgsh")
print(l2_list)
#方式三:列表推导式
-
增
- append 追加
list_data = ["SUN","三星","西门子","IBM"] ##append 追加 list_data.append("JAVA") print(list_data) 例子: while 1: msg = input("输入:(按q或Q退出)") if msg.upper() == "Q": break list_data.append(msg) print(list_data)
- insert 插入
list_data = ["SUN","三星","西门子","IBM"] list_data.insert(2,"apple") print(list_data)
- extend 迭代追加
list_data.extend("abc") print(list_data)
-
删
- pop 按照索引删除
list_data = ["SUN","三星","西门子","IBM"] ## pop 按照索引删除,默认删除最后一个元素 list_data.pop(1) print(list_data)
- remove 指定元素删除
list_data = ["SUN","三星","西门子","IBM","SUN"] list_data.remove("SUN") print(list_data) #列表有重复元素,默认只删除第一个
- clear 清空
list_data = ["SUN","三星","西门子","IBM","SUN"] list_data.clear() print(list_data)
- del
list_data = ["SUN","三星","西门子","IBM","SUN","apple"] #按照索引删除 del list_data[-1] print(list_data) #切片删除(步长) del list_data[1:4:2] print(list_data)
-
改
- 按照索引修改
list_data = ["SUN","三星","西门子","IBM","SUN","apple"] list_data[0] = "HUAWEI" print(list_data)
- 按照切片修改
list_data[::2] = "abc" print(list_data) #加上步长后,要修改的元素要一一对应;不加步长可以修改任意多的元素
-
查
- 按照索引查询
- 按照切片查询(步长)
- for循环
4 列表的嵌套
实例
msg = [1,2,"SUN","HUAWEI",[1,"APPLE","IBM"]]
## 将SUN变为小写
msg[2] = msg[2].lower()
print(msg)
##在小列表中追加一个元素
msg[-1].append("TAB")
print(msg)
## 将列表中的IBM通过字符串的方式在列表中变成IBMGOOD
msg[-1][-1] = msg[-1][-1] + "GOOD"
msg[-1][-1] += "GOOD"
print(msg)