一、创建列表
列表:
数组:存储同一数据类型的集合 score = [10,20,30]
列表:可以存储任意数据类型的集合
创建列表:
Name = ['Apache','Http','samba']
print(Name)
列表里可以存储不同的数据类型:
Lie = [1,1.3,'hello',True]
print(Lie,type(Lie))
列表嵌套
Lie = [1,1.3,'hello',True,[1,2,3]]
print(Lie,type(Lie))
二、列表的特性
1、索引
service = ['http','ssh','ftp','dns']
print(service[0])
print(service[1])
2、切片
service = ['http','ssh','ftp','dns']
print(service[1:]) ##除过列表的第一个元素都打印
print(service[:-1]) ##除过列表的最后一个元素都打印
print(service[::-1]) ##将列表的元素倒叙打印
3、重复
service = ['http','ssh','ftp','dns']
print(service * 2)
4、连接
service = ['http','ssh','ftp','dns']
service1 = ['mysql','firewalld']
print(service + service1)
5、成员操作符
service = ['http','ssh','ftp','dns']
service1 = ['mysql','firewalld']
print('mysql' in service)
print('mysql' in service1)
6、迭代(for循环)
service = ['http','ssh','ftp','dns']
service1 = ['mysql','firewalld']
print('显示所有服务'.center(50,'#'))
for S in service:
print(S)
7、列表里嵌套列表
service = [['http',80],['ssh',22],['ftp',21]]
print(service[0][1])
print(service[-1][1])
print(service[:][1])
print(service[-1][0])
print(service[0][:-1])
三、列表的增加
1、
service = ['http','ssh','ftp','dns']
print(service + ['firewalld'])
2、追加一个元素到列表中
service = ['http','ssh','ftp','dns']
service.append('firewalld')
print(service)
3、拉伸,追加多个元素到列表中
service = ['http','ssh','ftp','dns']
service.extend(['mysql','firewalld'])
print(service)
4、在指定索引位置插入元素
service = ['http','ssh','ftp','dns']
service.insert(1,'samba')
print(service)
四、列表的删除
1、删除最后一个索引值代表的元素
service = ['http','ssh','ftp','dns']
a = service.pop()
print(a)
print(service)
2、删除指定元素
service = ['http','ssh','ftp','dns']
a = service.remove('ssh')
print(a)
print(service)
3、从内存中删除列表
service = ['http','ssh','ftp','dns']
print(service)
del service
print(service)
五、列表的修改
1、通过索引,重新赋值
service = ['http','ssh','ftp','dns']
service[0] = 'mysql'
print(service)
2、通过切片
service = ['http','ssh','ftp','dns']
print(service[:2])
service[:2] = ['samba','nfs']
print(service)
六、列表的查看
1、查看的次数
service = ['ftp','ssh','ftp','dns']
print(service.count('ftp'))
print(service.count('dns'))
2、查看指定元素的索引值(可以指定索引范围查看)
service = ['ftp','ssh','ftp','dns']
print(service.index('ssh'))
print(service.index('ftp',1,4))
七、列表的排序
1、排序
import random
li = list(range(10))
print(li)
sort 与 sorted 区别:
sort 是应用在 list 上的方法,sorted 可以对所有可迭代的对象进行排序操作。
list 的 sort 方法返回的是对已经存在的列表进行操作,无返回值,而内建函数 sorted 方法返回的是一个新的 list,而不是在原来的基础上进行的操作。
#sorted保留原列表
li = [0,5,8,2,3,7,9]
a = sorted(li)
print(li)
print(a)
#sort
b = [5,2,3,1,7,9,8]
b.sort()
print(b)
2、打乱排序
import random
li = list(range(10))
print(li)
#讲原有的列表顺序打乱
random.shuffle(li)
print(li)