列表
数据类型的分类
可变(不可哈希)的:list dict set
不可变(可哈希)的:str bool int tuple
1. 列表的创建
方法一:
l1 = [1,2,"哈哈哈"]
方法二:
li = list()
方法三:列表推导式
2. 增
- append
- insert
- extend
li = ["520","Python",123] li.append("Faye") print(li.append("append方法增加")) #不能打印它,结果是None print(li) li.insert(1,"哈哈哈") #按索引插入,把“哈哈哈”插入到索引为1的位置 print(li) li.extend("ABC123") #extend是迭代增加 print(li)
None ['520', 'Python', 123, 'Faye', 'append方法增加'] ['520', '哈哈哈', 'Python', 123, 'Faye', 'append方法增加'] ['520', '哈哈哈', 'Python', 123, 'Faye', 'append方法增加', 'A', 'B', 'C', '1', '2', '3']
要特别注意extend和append的区别!
li = ["苹果","香蕉","菠萝"] li.extend(["番茄","青菜"]) print(li) li.append(["中国","上海"]) print(li)
['苹果', '香蕉', '菠萝', '番茄', '青菜'] ['苹果', '香蕉', '菠萝', '番茄', '青菜', ['中国', '上海']]
3.删
- pop() 返回删除的元素,再删
- remove() 指定元素删除,如果有多个元素,删除(从左到右数的)第一个
- clear() 清空,变成一个空列表了,但是列表还在
- del() 可以删除内容也可以删除整个列表
#pop() li = ["苹果","香蕉","菠萝","火龙果","西瓜","柿子"] print(li.pop()) #默认删除最后一个元素 print(li.pop(2)) #按索引删 print(li)
柿子 菠萝 ['苹果', '香蕉', '火龙果', '西瓜']
#remove() li = ["苹果","香蕉","苹果","西瓜"] li.remove("苹果") print(li)
['香蕉', '苹果', '西瓜']
#clear li = ["苹果","香蕉","苹果","西瓜"] li.clear() print(li)
[]
#del li = ["苹果","香蕉","菠萝","苹果","西瓜","水蜜桃","橘子"] del li[3] #按索引删 print(li) del li[::3] #按切片删 print(li) del li #把这个li删了。print(li)会报错
['苹果', '香蕉', '菠萝', '西瓜', '水蜜桃', '橘子'] ['香蕉', '菠萝', '水蜜桃', '橘子']
4.改
- 直接改
- 切片改
#直接改 li = ["苹果","香蕉","水蜜桃","橘子"] li[-2] = "hhhh" print(li)
['苹果', '香蕉', 'hhhh', '橘子']
#切片改 li = ["苹果","香蕉","菠萝","苹果","西瓜","水蜜桃","橘子"] li[2:] = "hh" print(li)
['苹果', '香蕉', 'h', 'h']
如果要变成 li = ["苹果","香蕉","hh"] 怎么办呢?
#方法一: li = ["苹果","香蕉","菠萝","苹果","西瓜","水蜜桃","橘子"] del li[2:] li.append("hh") print(li)
#方法二 li = ["苹果","香蕉","菠萝","苹果","西瓜","水蜜桃","橘子"] li[2:]=['hh']
5.查
- 按索引
- 按切片
li = ["苹果","香蕉","菠萝","苹果","西瓜","水蜜桃","橘子"] print(li[-3]) print(li[::2])
西瓜 ['苹果', '菠萝', '西瓜', '橘子']