01.列表的创建
数组:存储同一数据类型的集合 score = [10,20,30]
列表:可以存储任意数据类型的集合
例:
li = [1,1.2,'hello',True]
print(li)
print(type(li))
列表是可以嵌套的
li1 = [1,1.2,'hello',True,[1,2,3,4,5]]
print(li1)
print(type(li1))
02.列表的特性
service = ['http','ssh','ftp','dns']
1.索引
print(service[0])
print(service[-1])
2.切片
print(service[1:])
print(service[:-1])
print(service[::-1])
3.重复
print(service * 3)
4.连接
service1 = ['mysql','firewalld']
print(service + service1)
5.成员操作符
print('mysql' in service)
print('mysql' in service1)
6.迭代
print('显示所有服务'.center(50,'*'))
for se in service:
print(se)
03.列表里嵌套列表
service2 = [['http',80],['ssh',22],['ftp',21]]
#索引
print(service2[0][1])
print(service2[-1][1])
#切片
print(service2[:][1])
print(service2[:-1][0])
print(service2[0][:-1])
04.练习
要求:
“”"
假定有下面的列表:
names = [‘fentiao’,‘fendai’,‘fensi’,‘apple’]
输出结果为: ‘I have fentiao, fendai, fensi and apple.’
“”"
实现:
names = ['fentiao','fendai','fensi','apple']
print('I have ' + ','.join(names[:-1]) + ' and ' + names[-1])
05.列表的增加
service = ['http','ssh','ftp','dns'] ##原始的列表
#1.
print(service + ['firewalld']) ##输出时直接加一个元素
#2.append:追加 追加一个元素到列表中
service.append('firewalld')
print(service)
#3.extend:拉伸 追加多个元素到列表中
service.extend(['mysql','firewalld'])
print(service)
#4.insert:在指定索引位置插入元素
service.insert(1,'samba')
print(service)
06.列表的删除
In [19]: service = ['http','ssh','ftp','dns']
In [20]: service.pop() ##默认弹出最后一个元素
Out[20]: 'dns'
In [21]: service
Out[21]: ['http', 'ssh', 'ftp']
In [22]: a = service.pop() ##删除的元素仍然保存
In [23]: service
Out[23]: ['http', 'ssh']
In [24]: a ##可以调用
Out[24]: 'ftp'
In [25]: service.pop(0) ##可以删除指定索引的元素
Out[25]: 'http'
In [26]: service
Out[26]: ['ssh']
In [27]: service.pop()
Out[27]: 'ssh'
In [28]: service.pop() ##空的列表无法删除
------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-28-d8278ea86206> in <module>
----> 1 service.pop()
IndexError: pop from empty list
#remove:删除指定元素
In [30]: service = ['http','ssh','ftp','dns']
In [31]: a = service.remove('ssh')
In [32]: print(service)
['http', 'ftp', 'dns']
In [33]: print(a) remove删除后元素将不存在
None
In [34]: print(service)
['http', 'ftp', 'dns']
#从内存中删除列表
In [35]: del service ##删除整个列表
In [36]: print(service)
07.列表的修改
service = ['http','ssh','ftp','dns']
#通过索引,重新赋值
service[0] = 'mysql'
print(service)
#通过切片
print(service[:2])
service[:2] = ['samba','nfs'] ##将前两个元素修改
print(service)
08.列表的查看
service = [‘ftp’,‘ssh’,‘ftp’,‘dns’]
#查看出现的次数
print(service.count('ftp'))
print(service.count('dns'))
#查看指定元素的索引值(可以指定索引范围查看)
print(service.index('ssh'))
print(service.index('ftp',1,4)) ###范围为索引值
09.列表的排序
service = ['ftp','ssh','ftp','dns']
service.sort() ##在原位重新排列列表
print(service)
import random
li = list(range(10))
print(li)
#讲原有的列表顺序打乱
random.shuffle(li)
print(li)