python學習 lesson6 列表
一、列表的建立
li = [1,12,1.2,‘hello’,True]
print(li,type(li))
二、列表的特性
team = [‘bayern’, ‘barca’, ‘roma’]
索引
正向索引
print(team[0])
反向索引
print(team[-3])
切片
print(team[:])
print(team[1:])
print(team[::-1])
重複
print(team * 2)
連線
team1 = [‘changanjingji’, ‘hengda’, ‘shanggang’]
print(team + team1)
成員操作符
print(‘bayern’ in team)
print(‘bayern’ not in team)
巢狀列表
who = [[‘barca’,‘messi’],[‘bayern’,‘Robben’]]
索引
print(who[1][1])
切片
print(who[:1][:])
service = [‘ftp’,‘http’,‘ssh’,‘ftp’]
列表元素的增加
方法1 append():追加 追加一個元素到列表中,預設追加位置在列表最後一位
service.append(‘firewalld’)
print(service)
方法2 insert():插入 插入一個元素到指定位置
service.insert(2,‘mysql’)
print(service)
方法3 extend():拉神 追加多個元素到列表中
service.extend([‘zr’,‘kris’])
print(service)
列表元素的刪除
service = [‘ftp’,‘http’,‘myaql’,‘ftp’]
方法1 pop:取出 預設取出列表內最後一個元素,特點是可以儲存元素的值在記憶體中。
service.pop()
print(service)
a = service.pop(0)
print(service)
print(a)
方法2 remove:刪除 刪除列表中指定內容的元素且不能儲存,若元素內容相同則刪除索引值最小元素。
service = [‘ftp’,‘http’,‘myaql’,‘ftp’]
service.remove(‘ftp’)
print(service)
方法3 del:從記憶體中刪除
service = [‘ftp’,‘http’,‘myaql’,‘ftp’]
del service[1]
del service
print(service)
列表元素的修改
service = [‘ftp’,‘http’,‘myaql’,‘ftp’]
#1.通過索引重新賦值
service[0] = ‘mysql’
print(service)
#2.通過切片重新賦值
service[:2] = [‘zrr’,‘kris’]
print(service)
‘’’
###列表元素的檢視
service = [‘ftp’,‘http’,‘mysql’,‘ftp’,‘ftp’,‘ftp’,‘ftp’]
#查看出現次數
print(service.count(‘ftp’))
#檢視指定元素索引值
print(service.index(‘ftp’))
print(service.index(‘ftp’,1,4))
#排序檢視