python列表的增刪改查


 

列表的增

append()、insert()、extend(  )方法

append()方法:在末尾添加元素

 

s=['how','are','you']
s.append('fine')
print(s)

['how', 'are', 'you', 'fine']

 

insert()方法:在指定位置添加元素或者列表

s=['how','are','you']
s.insert(3,'fine')
print(s)

['how', 'are', 'you', 'fine']

 

 

extend()方法:可迭代,分解成元素添加在末尾。

s = ['how', 'are', 'you']
s.extend('fine')
print(s)

['how', 'are', 'you', 'f', 'i', 'n', 'e']

 

pop()、remove()、clear()、del

pop()方法: 按照下標索引刪除指定的值

s = ['how', 'are', 'you']
s.pop(0)
print(s)

['are', 'you']

 

remove()方法:按元素刪除指定的值

s = ['how', 'are', 'you']
s.remove('are')
print(s)

['how', 'you']

 

clear()方法:清空列表內數據

 

s = ['how', 'are', 'you']
s.clear()
print(s)

[]

 

 

 

del:刪除列表、也可以進行切片刪除

刪除列表:

s = ['how', 'are', 'you']

del [s]
打印結果為空
切片刪除: s
= ['how', 'are', 'you'] del s[0:2] print(s)
s
= ['how', 'are', 'you'] s[1]="old" print(s) ['how', 'old', 'you']

 

s[  ] = '  '  #元素賦值 

 
         
li = [1,2,3,5,'cat',2,3,4,5,'bye']
li[3]='monkey'

print(li)
 
s[0:2] =  ‘  ’  #分片賦值 

# li = [1,2,3,5,'cat',2,3,4,5,'bye']
# li[0:2]=('a')
# print(li)
 
 

查:查詢列表可通過下標和切片的方式

 
        
1.下標取值索引,從0開始

names = ['mike','mark','candice','laular']

print(names[2])


candice
2.切片:顧頭不顧尾,且切片下標的操作同樣用於字符串 names = ['mike','mark','candice','laular'] print(names[1:3]) #通過切片方式取值,切片是顧頭不顧尾,打印結果:['mark', 'candice'] print(names[1:]) #取下標后面所有的值,打印結果:['mark', 'candice', 'laular'] print(names[:3]) #取下標前面所有的值,打印結果:['mike', 'mark', 'candice'] print(names[:]) #取所有的值,打印結果:['mike', 'mark', 'candice', 'laular'] print(names[-1]) #取最后一個值,打印結果:laular print(names[:1:2])#隔幾位取一次,默認不寫步長為1,即隔一位取一次;結果為取下標為1之前的值,隔2位取一個['mike']
 
        

列表其他方法

 
        
index()方法:獲取指定元素的下標

s = ['how', 'are', 'you']
s1=s.index('are')

print(s1) 獲取的元素下標為1 注:列表中s.find()不可用作獲取元素的下標。
count()方法:計算元素出現的次數 s = ['how', 'are', 'you','you'] s1=s.count('you') print(s1)
2
sort()方法:進行排序,默認是正向排序,想要反向排序需要加:(reverse=True) ,reverse返轉的意思 正向排序: s=[1,4,8,5,6,2,3] s.sort() print(s1)
[
1, 2, 3, 4, 5, 6, 8] 此時默認reverse=false
反向排序:
當reverse
=True時, s=[1,4,8,5,6,2,3] s.sort(reverse=True) print(s)
[
8, 6, 5, 4, 3, 2, 1]
翻轉:
s
=[1,4,8,5,6,2,3] s.reverse() print(s)
[
3, 2, 6, 5, 8, 4, 1]

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM