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))
運行結果: