列表元素的增加,刪除,修改,檢視
1.列表元素的增加
service = [‘http’, ‘ssh’, ‘ftp’]
1.直接新增元素
print(service + [‘firewalld’])
append:追加,追加一個元素到列表中
service.append(‘firewalld’)
print(service)
extend:拉伸,追加多個元素到列表中
service.extend([‘hello’,‘python’])
print(service)
insert:在索引位置插入元素
service.insert(0,‘firewalld’)
print(service)
列表的刪除
service = [‘http’, ‘ssh’, ‘ftp’]
remove
service.remove(‘ftp’)
print(service)
service.remove(‘https’)
print(service)
claer:清空列表裡面的所有元素
service.clear()
print(service)
del(python關鍵字) 從記憶體中刪除列表(只能刪除索引指定的元素)
del service[1]
print(service)
print(‘刪除前兩個元素之外的其他元素:’,end=’’)
del service[2:]
print(service)
彈出元素pop
彈出第一個元素:
service.pop(1)
print(service)
列表元素的修改
service = [‘ftp’,‘http’, ‘ssh’, ‘ftp’]
通過索引,重新賦值
將第一個元素改變
service[0] = ‘mysql’
print(service)
通過slice(切片)
將前兩個元素進行改變
service[:2] = [‘mysql’,‘firewalld’]
print(service)
元素的檢視
檢視元素出現的次數
print(service.count(‘ftp’))
檢視指定元素的索引值(也可以指定範圍)
print(service.index(‘ssh’))
print(service.index(‘ssh’,4,8))
排序檢視(按照ascii碼進行由大到小排序)
print(service.sort(reverse=True))
print(service)
對字串排序不區分大小寫(按照由小到大排序)
phones = [‘alice’,‘bob’,‘harry’,‘Borry’]
phones.sort(key=str.lower)
phones.sort(key=str.upper)
print(phones)