1.创建列表
数组:存储同一数据类型的集合 score = [10,20,30]
列表:可以存储任意数据类型的集合
In [16]: name = ['tom','bob','coco','alice']
In [17]: name
Out[17]: ['tom', 'bob', 'coco', 'alice']
In [18]: type(name)
Out[18]: list
- 列表里可以存储不同的数据类型
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))
2.列表的特性
- 索引
service = ['http','ssh','ftp','dns']
print(service[0])
print(service[-1])
- 切片
service = ['http','ssh','ftp','dns']
print(service[1:])
print(service[:-1])
print(service[::-1])
- 重复
service = ['http','ssh','ftp','dns']
print(service * 3)
- 连接
service = ['http','ssh','ftp','dns']
service1 = ['mysql','firewalld']
print(service + service1)
- 成员操作符
service = ['http','ssh','ftp','dns']
service1 = ['mysql','firewalld']
print('mysql' in service)
print('mysql' in service1)
- 迭代
service = ['http','ssh','ftp','dns']
service1 = ['mysql','firewalld']
print('显示所有服务'.center(50,'*'))
for se in service:
print(se)
- 列表里嵌套列表
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])
3.列表的增加
5.列表的删除
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]:
In [31]: a = service.remove('ssh')
In [32]: print(service)
['http', 'ftp', 'dns']
In [33]: print(a)
None
In [34]: print(service)
['http', 'ftp', 'dns']
#从内存中删除列表
In [35]: del service
In [36]: print(service)
6.列表的修改
7.列表的查看
8.列表的排序
8.列表练习
1)题目:
假定有下面的列表:
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])
2)题目:
1.系统里面有多个用户,用户的信息目前保存在列表里面
users = [‘root’,‘westos’]
passwd = [‘123’,‘456’]
2.用户登陆(判断用户登陆是否成功
1).判断用户是否存在
2).如果存在
1).判断用户密码是否正确
如果正确,登陆成功,推出循环
如果密码不正确,重新登陆,总共有三次机会登陆
3).如果用户不存在
重新登陆,总共有三次机会
users = ['root','westos']
passwords = ['123','456']
#尝试登录次数
trycount = 0
while trycount < 3:
inuser = input('用户名: ')
inpassword = input('密码: ')
trycount += 1
if inuser in users:
index = users.index(inuser)
password = passwords[index]
if inpassword == password:
print('%s登录成功' %(inuser))
break
else:
print('%s登录失败 : 密码错误' %inuser)
else:
print('用户%s不存在' %inuser)
else:
print('尝试超过三次,请稍后再试')