1,更新列表
#coding:utf8
x1 = [1,2,3,4,5,6,7]
列表更新
x1 [2] ="hello"吧
2,增加元素:
使用append方法在列表的最后追加新元素,但注意append每次只能新增一个元素,如果想新增多个元素就要使用extend方法
x1.append("hello")
print(x1)
x1.append([6,7])
print(x1)
extend方法:
x1.extend([6,7])
3,在列表中间插入元素insert
x1.inset(2,"hello")
insert方法传递两个参数,第一个参数表示要插入的新元素的位置,第二个参数表示要插入的新元素。insert一次只能新增一个元素
4,删除元素
pop函数用于移除列表中的一个元素(默认是最后一个元素),并且返回该元素的值。
#coding:utf8
x1 = [1,2,3,4,5,6,7]
print(x1)
r1 = x1.pop()
print(r1)
print(x1)
print("...................")
x2 = [1,2,3,4,5,6,7]
print(x2)
r2 = x2.pop(2)
print(r2)
print(x2)
运行结果:
不但可以根据位置删除元素,还可以根据元素内容来对元素进行删除,remove方法就提供了这样的功能
#coding:utf8
x1 = ["hello","google","baidu"]
print(x1)
x1.remove("hello")
print(x1)
运行结果:
也可以使用关键字”del“ 来删除列表元素
5,查找元素
python提供了index方法用于查找元素在列表中的索引位置
#coding:utf8
x1 = ["hello","google","baidu"]
print("baidu index is",x1.index("baidu"))
运行结果:
6, 反转队列
reverse方法无返回值
#coding:utf8
x1 = [1,2,3,4,5,6,7]
print(x1)
x1.reverse()
print(x1)
运行结果:
7,count方法用于统计某个元素在列表中出现的次数
#coding:utf8
x1 = ["hello","google","baidu","hello","baidu","hello"]
print(x1)
print(x1.count("hello"))
print(x1.count("baidu"))
运行结果:
8,sort方法用于对列表进行排序,还可以自定义排序方式,没有返回值
# coding:utf8
x1 = [1, 2, 3, 4, 5, 6, 7]
print(x1)
x1.sort()
print(x1)
print(type(x1))
运行结果: