(5)Python——列表

1.列表和数组的区别:

数组:存储同一数据类型的集和

列表:存储不同数据类型的同一集和

2.列表的特性

service = ['http','ssh','ftp','dns']

1)索引

service[0]   #列表第一个
service[-1]  #列表倒数第一个

2)切片

service[1:]   #2到最后
service[:-1]  #除了最后一个
service[::-1] #倒序

3)重复

service * 2

4)连接

service1 = ['mysql','firewalld']
service + service1

5)

目标是否在列表中,如果在返回True,如果不在返回False

'mysql' in service
'mysql' in service1

6)迭代:循环遍历

print('显示所有服务'.center(50,'*'))
for se in service:
     print(se)

3.列表里嵌套列表

service2 = [['http',80],['ssh',22],['ftp',21]]

1)索引

service2[0][1]  #第一层列表里的第一个列表,中的第二个
service2[-1][1] #第一层列表里的倒数第一个列表,中的第二个

2)切片

print(service2[:][1])
print(service2[:-1][0])
print(service2[0][:-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])

4.列表的增加

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)

5.列表的删除

service = ['http','ssh','ftp','dns']

1)弹出pop

弹出的值可以继续使用

out=service.pop()
print(out)

弹出指定元素:

a=service.pop(0) #弹出第一个
print(a) 

2)remove:删除指定元素

清空内存地址(从内存中直接删除)

a = service.remove('ssh')
print(service)

3)从内存中删除列表

del service
print(service) 

6.列表的修改

service = ['http','ssh','ftp','dns']

1)通过索引,重新赋值

service[0] = 'mysql'
print(service)

2)通过切片,重新赋值

print(service[:2])
service[:2] = ['samba','nfs']
print(service

7.列表的查看

service = ['ftp','ssh','ftp','dns']

1)查看出现的次数

print(service.count('ftp'))
print(service.count('dns'))

2.查看指定元素的索引值(可以指定索引范围查看)

print(service.index('ssh'))
print(service.index('ftp',1,4))  #1-4内查找

8.列表的排序

1)sort()函数排序:默认ASCII码排序

2)将原有的列表顺序打乱

import random

li = list(range(10)) #输出1-10
print(li)

random.shuffle(li)  #打乱顺序
print(li)

9.实例:

1)用户管理

"""
1.系统里面有多个用户,用户的信息目前保存在列表里面
    users = ['root','westos']
    passwd = ['123','456']
2.用户登陆(判断用户登陆是否成功
    1).判断用户是否存在
    2).如果存在
        1).判断用户密码是否正确
        如果正确,登陆成功,推出循环
        如果密码不正确,重新登陆,总共有三次机会登陆
    3).如果用户不存在
    重新登陆,总共有三次机会
"""
users = ['root','westos']
passwords = ['123','456']

#尝试登录次数
count = 0

while count < 3:
    inuser = input('用户名: ')
    inpassword = input('密码: ')

    count += 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('尝试超过三次,请稍后重试')

猜你喜欢

转载自blog.csdn.net/weixin_44214830/article/details/89036823