目录
一、列表特点:
1、索引从0开始
2、列表是有序的
3、可变的
4、元素可以重复
5、同一list支持任意数据类型
6、列表都可以进行的操作包括索引,切片,加,乘,检查成员
二、列表操作
1、新增/创建
创建一个列表,只要把逗号分隔的不同的数据项使用方括号括起来即可
list1 = ['test1', 'hello', 1, 2]
list2 = [1, 2, 3, 4, 5 ]
list3 = ["a", "b", "c", "d"]
list4 = ['red', 'green', 'blue', 'yellow', 'white', 'black']
2、 删除常用方法
2.1 list.pop(index)
index = None:删除最后一个元素
index = 索引值 :删除对应索引的元素
正确删除返回被删除的元素
list_1 = [1, 2, 3, 4, 5, 6]
result = list_1.pop() # 不传索引值默认删除最后的元素
print(result) # 接受返回的参数并输出
print(list_1)
list_1.pop(0) # 传索引值,删除指定的元素
print(list_1)
2.2 list.remove()
删除匹配到的第一个元素
如果匹配元素失败,直接报错
正确删除了返回None
list_1 = [1, 2, 2, 2, 3, 4, 5, 6]
list_1.remove(2) # 只移除匹配到的第一个元素
print(list_1) # 输出移除数据后的列表数据
list_1.remove(5) # 传元素值,删除指定的元素
print(list_1) # 输出删除指定元素后的列表
2.3 del list[index]
index:索引值,按索引删除,没有返回值
list_1 = [1, 2, 2, 2, 3, 4, 5, 6]
del list_1[2] # 传单个索引
print(list_1)
del list_1[0:2] # 传切片范围
print(list_1)
2.4 clear() 清空列表
list_1 = [1, 2, 2, 2, 3, 4, 5, 6]
list_1.clear() # 传单个索引
print(list_1)
3、修改常用方法
3.1 修改元素的值
list_1[index] = value
list_1 = [1, 2, 3, 4, 5, 6]
list_1[0] = 'res' # 把列表的第一位元素改为res
print(list_1)
3.2 list_1.append(元素) 常用
list_1 = [1, 2, 3, 4, 5, 6]
list_1.append(7) # 在末尾添加元素7
print(list_1)
3.3 list_1.insert(索引值,元素)
索引值:插入后元素的索引,其他元素索引自增
list_1 = [1, 2, 3, 4, 5, 6]
list_1.insert(0, 'python')
print(list_1)
3.4 list_1.extend(list_2)
将list_2里面所有的元素一个个追加到(append)写入发到list_1
list_1 = [1, 2, 3, 4, 5, 6]
list_2 = ['a', 'b', 11, 12]
list_1.extend(list_2)
print(list_1)
3.5 +
(list_3=list_1+list_2) list合并,生成新的list,不修改原有List 常用
list_1 = [1, 2, 3, 4, 5, 6]
list_2 = ['a', 'b', 11, 12]
list_3 = list_1 + list_2
print(list_3)
4、查询常用方法
4.1通过索引获取元素 list[index]
4.2获取元素索引值 list_1.index(value)
4.3 获取列表长度 len(list_1)
4.5 切片 list[开始索引:结束索引:步长]
list_1 = [1, 2, 3, 4, 5, 6]
print(list_1[0]) # 输出单个元素
print(list_1.index(6)) # 查看元素6的索引值
print(len(list_1)) # 字符串长度
print(list[0:3]) # 切片