列表可以存储任意数据类型
列表的表示类型的查看
sit = [1,2,3.4,True,'fangyuan']
print(lsit)
priint(type(list))
#打印结果
[1, 2, 3.4, True, 'fangyuan']
<class 'type'>
切片
service = ['http','ftp','ssh']
print(service[0])
print(service[::-1])
print(service[1:])
print(service[:-1])
#打印结果
http
['ssh', 'ftp', 'http']
['ftp', 'ssh']
['http', 'ftp']
追加元素
#追加元素
service = ['http','ftp','ssh']
service.append('firewall')
print(service)
#拉伸增加多个元素
service.extend(['mysql','nfs'])
print(service)
#指定索引处添加
service.insert(1,'https')
print(service)
#打印结果
['http', 'ftp', 'ssh', 'firewall']
['http', 'ftp', 'ssh', 'firewall', 'mysql', 'nfs']
['http', 'https', 'ftp', 'ssh', 'firewall', 'mysql', 'nfs']
删除
service = ['http','ftp','ssh','https']
service.pop() #弹出最后一个元素
print(service)
service.pop(0) #删除索引元素
print(service)
service.remove('ssh') #删除指定元素
print(service)
del service[0] #从内存中删除一个元素
print(service)
#打印结果
['http', 'ftp', 'ssh']
['ftp', 'ssh']
['ftp']
[]
元素的查看
service = ['http','ftp','ssh','http','ftp','ssh']
# 查看元素在列表中出现的次数
print(service.count('ftp'))
# 查看指定元素的索引值(可以指定索引范围)
print(service.index('ssh'))
print(service.index('ssh',4,7))
#打印结果
2
2
5
排序
service = ['http','ftp','ssh']
# 默认按照Ascii码进行排序
service.sort(reverse=True)
print(service)
phones = ['Tom','alice','bob','Borry']
phones.sort(key=str.upper)
#统一大小写排序
print(phones)
#打印结果
['ssh', 'http', 'ftp']
['alice', 'bob', 'Borry', 'Tom']
修改
service = ['ftp','http','ftp','ssh','mysql']
# 通过索引值,重新赋值
service[0] = 'samba'
print(service)
# 通过切片赋值
print(service[:2])
service[:2] = ['mysql','nginx','nfs']
print(service)
#打印结果
['samba', 'http', 'ftp', 'ssh', 'mysql']
['samba', 'http']
['mysql', 'nginx', 'nfs', 'ftp', 'ssh', 'mysql']