python中的列表
一.列表的定义
1.定义一个列表
li = [1,1.2,True,'hello']
print li
print type(li)
2.定义一个空列表
li=[]
print li
print type(li)
二.列表的特性
1.索引
service = ['http', 'ssh', 'ftp']
print service[0]
print service[-1]
2.切片
service = ['http', 'ssh', 'ftp']
print service[::-1] # 列表的翻转
print service[1:] # 除了第一个元素之外的其他元素
print service[:-1] # 除了最后一个元素之外的其他元素
3.重复和连接
service = ['http', 'ssh', 'ftp']
print service * 3
service1 = ['mysql','firewalld']
print service + service1
4.成员操作符
service = ['http', 'ssh', 'ftp']
print 'firewalld' in service
print 'firewalld' in service1
print 'firewalld' not in service
5.for循环遍历列表
service = ['http', 'ssh', 'ftp']
print '显示服务'.center(50,'*')
for se in service:
print se
6.列表里可以嵌套列表
service2 = [['http',80],['ssh',22],['ftp',21]]
print service2,type(service2)
7.嵌套的索引
print service2[0][1]
print service2[-1][1]
8.嵌套的切片
print service2[:][1]
print service2[:-1][0]
print service2[0][:-1]
三.列表的操作
1.增加
(1).输出追加
service = ['http', 'ssh', 'ftp']
print service + ['firewalld']
(2).append()——适用于单个元素的添加
service = ['http', 'ssh', 'ftp']
service.append('firewalld')
print service
(3).extend()——适用于多个元素的添加
service = ['http', 'ssh', 'ftp']
service.extend(['mysql', 'firewalld'])
print service
(4).insert()——在指定索引位置后插入元素
service = ['http', 'ssh', 'ftp']
service.insert(1,'samab')
print service
2.删除
(1).pop()
service = ['http', 'ssh', 'ftp']
print service.pop() ## 如果pop()不传递值的时候,默认弹出最后一个元素
service = ['http', 'ssh', 'ftp']
print service.pop(1) ## 如果给pop()传递值,弹出相关索引值的元素
(2).remove()——删除指定元素
service = ['http', 'ssh', 'ftp']
service.remove('ssh')
print service
(3).关键字del——从内存中删除列表
service = ['http', 'ssh', 'ftp']
print service
del service
print
service
3.修改
(1).通过索引重新赋值
service = ['http', 'ssh', 'ftp']
service[0] = 'mysql'
print service
(2).通过切片,重新赋值
service = ['http', 'ssh', 'ftp']
print service[:2]
service[:2] = ['samba','ladp']
print service
4.查看
(1).查看元素在列表中出现的次数
service = ['http', 'ssh', 'ftp','ftp']
print service.count('ssh')
(2).查看指定索引值的元素
service = ['http', 'ssh', 'ftp','ftp']
print service.index('ssh')
5.排序
service = ['http', 'ssh', 'ftp','ftp']
service.sort()
print service # 按照Ascii码进行排序