1. 程式人生 > >Python列表操作方法

Python列表操作方法

python 列表 Python列表 Python序列

Python列表操作方法

python的操作方法包括:創建、刪除、修改、查找等

'列表的相關操作'

1.創建列表

list=[0,'port',1,'error',2,'port']

print(id(list[1]))

2.刪除列表

list=[1,'port',1,'error',2,'port']

print(id(list[1]))

2.1刪除整個列表

del list

print(list)

2.2刪除列表元素

a=[1,4,'pool'

,8,'list']

1.使用list自帶的remove刪除元素值的方法進行

a.remove('pool')

print(a)

2.使用list自帶的pop刪除元素索引的方法進行

a.pop(1) #若不帶索引值,將會自動刪除最後一個值並返回刪除的最後一個值

print(a)

3.使用python的del函數進行刪除元素索引的方法進行操作

del(a[1])

print(a)

3.修改列表

3.1通過索引修改列表中的原元素

b=[2,6,'jian'

,'boom',8,9]

b[1]='Heart'

print(b)

3.2在列表原有的基礎上進行擴展操作

1.使用list自帶的insert方法進行插入新元素

b.insert(1,'one') #兩個參數,第一個為索引,第二個為需要插入的參數值

print(b)

2.使用list自帶的append方法進行插入,append是只會在列表的末尾插入一個元素操作

b.append('last')

print(b)

3.使用list自帶的extend方法進行插入,進行擴展列表

b.extend(2) #不支持數字

b.extend('add one') #字符串將會被分解,依次以一個字符串的形式被插入

print(b)

b.extend([2,5,'ppp']) #以列表參數擴充列表,每個元素都將會插入

print(b)

b.extend(('a','b','c','d',3,4,)) #以元組參數擴充列表,每個元素都將會插入

print(b)

b.extend({1:'error','b':89}) #以字典參數擴充列表,將只會把key插入,value值將不會被插入

print(b)

4.列表的其他操作

c=[3,'you',6,'done']

4.1切片操作

print(c[6:7])#當索引超出範圍後將輸出空的list

4.2索引

print(c[3])

4.3正序排列(按數值大小),不能將數字和字符串一起進行排序,否則會報錯

d=[2,6,4,89,0,23,-9,45,3]

d.sort()

print(d)

e=['er','ty','you','oiu','k','a']

print(e)

4.4逆序排列(按數值大小),不能將數字和字符串一起進行排序,否則會報錯

d.reverse()

print(d)

e.reverse()

print(e)

4.5 len(list):列表元素個數

print(len(d))

4.6 max(list):返回列表元素最大值,同類型比較

print(max(e))

4.7 min(list):返回列表元素最小值,同類型比較

print(min(d))

4.8 list(seq):將元組轉換為列表

5.列表的遍歷方法

f=[1,'ad','ki',9,'po',['d',12],90]

5.1使用索引來遍歷

for i in range(len(f)):

print(f[i])

5.2 使用列表中的值進行遍歷

for vau in f:

print(vau)

小結---列表操作常用操作包含以下方法:

2 list.append(obj):在列表末尾添加新的對象

3 list.count(obj):統計某個元素在列表中出現的次數

4 list.extend(seq):在列表末尾一次性追加另一個序列中的多個值(用新列表擴展原來的列表)

5 list.index(obj):從列表中找出某個值第一個匹配項的索引位置

6 list.insert(index, obj):將對象插入列表

7 list.pop(obj=list[-1]):移除列表中的一個元素(默認最後一個元素),並且返回該元素的值

8 list.remove(obj):移除列表中某個值的第一個匹配項

9 list.reverse():反向列表中元素

10 list.sort([func]):對原列表進行排序


Python列表操作方法