python中的数据类型——列表(list)

数值类型:int (long)
float
布尔型
字符串
列表(list)

python2中(int long):

在这里插入图片描述

python3中(int):

在这里插入图片描述

列表的定义

C语言中数组:存储同一种数据类型的集和 scores=[1,2,33,44]
列表(打了激素的数组):可以存储任意数据类型的集和

li = [1,2.2,True,'hello']
print(li,type(li))

列表里面是可以嵌套列表的

li = [1,2,3,False,'python',[1,2,3,4,5]]
print(li,type(li))

import random
li = list(range(10))
random.shuffle(li)
print(li)

列表的特性

索引

service = ['http','ssh','ftp']    #存在列表service

正向索引

print(service[0])

反向索引

print(service[-1])

索引的练习

例一:
根据用于指定月份,打印该月份所属的季节。
提示: 3,4,5 春季 6,7,8 夏季 9,10,11 秋季 12, 1, 2 冬季

month = int(input('Month:'))
if month in [3,4,5]:
    print('春季')
elif month in [6,7,8]:
    print('夏季')
elif month in [9,10,11]:
    print('秋季')
else:
    print('冬季')

例二:
假设有下面这样的列表:
names = [‘fentiao’,‘fendai’,‘fensi’,‘fish’]
输出的结果为:‘I have fentiao,fendai,fensi and fish’

names = ['fentiao','fendai','fensi','fish']
print('I have ' + ','.join(names[:-1]) + ' and ' + names[-1])

切片

print(service[::-1])  # 列表的反转
print(service[1::])   # 除了第一个之外的其他元素
print(service[:-1])   # 除了最后一个之外的其他元素

重复

print(service * 3)

连接

service1 = ['mysql','firewalld']
print(service + service1)

成员操作符

print('firewalld' in service)
print('ftp' in service)
print('firewalld' not in service)
print('ftp' not in service)

列表里面嵌套列表

service2 = [['http',80],['ssh',22],['ftp',21]]
print(service2[0][0])
print(service2[-1][1])

列表的增删改查

列表的增加

service = ['http', 'ssh', 'ftp']
print(service + ['firewalld'])

append:追加,追加一个元素到列表中

service.append('firewalld')
print(service)

extend:拉伸,追加多个元素到列表中

service.extend(['hello','python'])
print(service)

insert:在索引位置插入元素

service.insert(0,'firewalld')
print(service)

列表元素的删除

In [1]: li = [1,2,3,4]

pop()按索引值删除

In [2]: li.pop()
Out[2]: 4

In [3]: li.pop(0)
Out[3]: 1

In [4]: li.pop(3)
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-4-e9f9f299015e> in <module>()
----> 1 li.pop(3)

remove()按python关键字删除

service = ['http', 'ssh', 'ftp']
remove
service.remove('ftp')
print(service)
service.remove('https')
print(service)

claer:清空列表里面的所有元素

service.clear()
print(service)

del(python关键字) 从内存中删除列表

del service
print(service)
print('删除列表第一个索引对应的值:',end='')
del service[1]
print(service)
print('删除前两个元素之外的其他元素:',end='')
del service[2:]
print(service)

列表元素的修改

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

通过索引,重新赋值

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

通过slice(切片)

service[:2] = ['mysql','firewalld']
print(service)

列表元素的查看

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

查看元素出现的次数

print(service.count('ftp'))

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

print(service.index('ssh'))
print(service.index('ssh',4,8))

排序查看(按照ascii码进行排序)

print(service.sort(reverse=True))
print(service)

对字符串排序不区分大小写

phones = ['alice','bob','harry','Borry']
phones.sort(key=str.lower)
phones.sort(key=str.upper)
print(phones)

列表练习01——栈

stack = [1,2,3,4]
栈的工作原理:先进后出
入栈
出栈
栈顶元素
栈的长度
栈是否为空

stack = []

info = """
        栈操作
     1.入栈
     2.出栈
     3.栈顶元素
     4.栈的长度
     5.栈是否为空
"""

while True:
    print(info)
    choice = input('请输入选择:')
    if choice == '1':
        item = input('入栈元素:')
        stack.append(item)
        print('元素%s入栈成功' %(item))
    elif choice == '2':
        # 先判断栈是否为空
        if not stack:
            print('栈为空,不能出栈')
        else:
            item = stack.pop()
            print('元素%s出栈成功' %(item))
    elif choice == '3':
        if len(stack) == 0:
            print('栈为空,无栈顶元素')
        else:
            print('栈顶元素为%s' %(stack[-1]))
    elif choice == '4':
        print('栈的长度为%s' %(len(stack)))

    elif choice == '5':
        if len(stack) == 0:
            print('栈为空')
        else:
            print('栈不为空')
    elif choice == 'q':
        print('欢迎下次使用')
        break
    else:
        print('请输入正确的选择')

6.列表练习02——用户登录

1.系统里面有多个用户, 用户信息目前保存在列表里面:
users = [‘root’, ‘westos’]
passwds = [‘123’, ‘456’]
2.用户登陆(判断用户登陆是否成功):
1). 判断用户是否存在?(inuser in users)
2). 如果存在:
判断用户密码是否正确?
(先找出用户对应的索引值,根据passwds[索引值]拿出该用户的密码)
如果正确:登陆成功,退出循环;
如果密码不正确, 重新登陆,总共有三次登陆机会
3). 如果不存在:重新登陆, 总共有三次登陆机会

users = ['root', 'westos']
passwds = ['123', '456']

尝试登陆的次数

trycount = 0

while trycount < 3:
    inuser = input('用户名:')
    inpasswd = input('密码:')
    # 尝试次数加1
    trycount += 1
    if inuser in users:
        # 判断用户密码是否正确
        index = users.index(inuser)
        passwd = passwds[index]
        if inpasswd == passwd:
            print('%s登陆成功' % (inuser))
            break
        else:
            print('%s登陆失败:密码错误' % (inuser))
    else:
        print('用户%s不存在' % (inuser))
else:
    print('已经超过3次机会了~')

7.列表练习03——后台管理

1.后台管理员只有一个用户:admin;密码::admin
2.当管理员登陆成功后, 可以管理前台会员信息
会员信息管理包含:
1)添加会员信息
2)删除会员信息
3)查看会员信息
4)退出

users = ['root','redhat']
passwds = ['123','456']
inuser = input('请输入用户名:')
inpasswd = input('请输入密码:')
if inuser == 'admin' and inpasswd == 'admin':
    print('管理员登陆成功')
    while True:
        print("""
                操作选项
                1.添加会员信息
                2.删除会员信息
                3.查看会员信息
                4.退出
                """)

    choice = input('请输入操作选项:')
    if choice == '1':
        print('添加会员信息'.center(50,'*'))
        adduser = input('请输入要添加的会员名:')
        if adduser in users:
            print('会员名%s已存在' %(adduser))
        else:
            addpasswd = input('请输入密码:')
            users.append(adduser)
            passwds.append(addpasswd)
            print('添加用户%s成功!' % (adduser))

    elif choice == '2':
        print('删除会员信息'.center(50,'*'))
        deluser = input('请输入想要删除的会员名:')
        if deluser in users:
            delindex = users.index(deluser)
            users.remove(deluser)
            passwds.pop(delindex)
            print('删除用户%s成功' %(deluser))
        else:
            print('%s用户不存在' %(deluser))

    elif choice == '3':
        print('查看用户信息'.center(50,'*'))
        seeuser = input('请输入想要查看的用户信息:')
        if seeuser in users:
            print('\t用户名\t密码')
            seeindex = users.index(seeuser)
            print('\t%s\t%s' %(users[seeindex],passwds[seeindex]))

    elif choice == '4':
        print('退出登陆')
        exit()

    else:
        print('请输入正确的选项!')

else:
    print('管理员登录失败')

猜你喜欢

转载自blog.csdn.net/dodobibibi/article/details/84483424