列表
列表-----list-----容器(有序,可变,支持索引)
列表:存储数据,支持的数据类型很多(字符串,数字,布尔值,列表,集合,元组,字典)
#定义一个列表
lst = ["123","常青藤","九月风",123,True]
#用逗号分隔的是一个元素
print(lst[0])
print(id(lst[0])) #id获取对象的内存地址
lst = ["123","常青藤","九月风",123,True]
lst [0] = "996"
print(lst)
#输出 ["996","常青藤","九月风",123,True]
#字符串是不可变的数据
s = "alex" # 字符串是不可变数据
s = "wusir"
s[0] = "b"
print(s)
增加
1)追加:在列表的最后位置添加一个内容,关键词 append
lst = ["123","常青藤","九月风",123,True]
lst.append("冬日雪")
print(lst)
#输出 ['123', '常青藤', '九月风', 123, True, '冬日雪']
2) 插入:以后尽量不要使用(当数据量比较大的时候会影响效率)关键字词 insert
lst = ["123","常青藤","九月风",123,True]
lst.insert(1,"冬日雪")
print(lst)
#输出 ['123', '冬日雪', '常青藤', '九月风', 123, True]
3)迭代添加 关键词 extend(”可迭代的内容)
lst = ["123","常青藤","九月风",123,True]
lst.extend("夏季的雨")
print(lst)
# 输出 ['123', '常青藤', '九月风', 123, True, '夏', '季', '的', '雨']
删除
1)默认删除最后一个 关键词 pop
有返回值返回的是被删除的元素
dtu = ["123","常青藤","九月风",123,True]
dtu.pop()
print(dtu)
# 输出 ['123', '常青藤', '九月风', 123]
2)通过指定索引进行删除 关键词 pop(数字)
lta = ["123","常青藤","九月风",123,True]
lta.pop(2)
print(lta)
#输出 ['123', '常青藤', 123, True]
3) 移除 ,通过元素名字进行删除 关键词 remove(元素名)
lta = ["123","常青藤","九月份",123,True]
lta.remove(123)
print(lta)
#输出 ['123', '常青藤', '九月份', True]
4)通过索引删除 关键词 del
lta = ["123","常青藤","九月份",123,True]
del lta[1]
print(lta)
#输出 ['123', '九月份', 123, True]
通过切片删除
lta = ["123","常青藤","九月份",123,True]
del lta[0:2]
print(lta)
#输出 ['九月份', 123, True]
通过步长删除
lta = ["123","常青藤","九月份",123,True,"夏日雨",False]
del lta[0:5:2]
print(lta)
# 输出 ['常青藤', 123, '夏日雨', False]
清空 (关键字 clear)
lta = ["123",123,"春日雨","夏日阳","秋日果","冬日雪"]
lta.clear()
print(lta)
# 输出 []
改(元素可以超出切片的位数)
lta = ["123","常青藤","九月份",123,True,"夏日雨",False]
lta[1] = "冬日雪"
print(lta)
#输出['123', '冬日雪', '九月份', 123, True, '夏日雨', False]
lta = ["123","常青藤","九月份",123,True,]
lta[1:3] = "冬日雪"
print(lta)
#输出['123', '冬', '日', '雪', 123, True]
lta = ["123","常青藤","九月份",123,True,]
lta[1:4] = 12,13,14,15,16
print(lta)
#输出 ['123', 12, 13, 14, 15, 16, True]
lta = ["123","常青藤","九月份",123,True,]
lta[1:4:2 ]="12"
print(lta)
#输出 ['123', '1', '九月份', '2', True]
- 步长不为1的必须要一一对应,多一个不行,少一个也不行
查
for循环
lta = ["123","常青藤","九月份",123,True,]
for i in lta:
print(i)
#输出
123
常青藤
九月份
123
True
列表的嵌套
取值通过索引进行取值,一层一层的进行查找
lst = [1,"alex","999","小东北","渣渣",
["大黑",["小七",["我帅吗"],"大煎饼","掉井盖","三金片"],
"海棠","海马",["太白金星","女神","九月",["110"]]]]
print(lst[-1][1][1][0])
#输出 我帅吗