Python05 数据序列-列表

Python05 数据序列-列表

5.1 列表概述

python列表是一种有序且可变的序列,列表使用中括号[]进行定义,各项元素之间使用逗号分隔。python的列表与其他编程语言中的数组很像,但独特之处在于python可以存储任意类型的数据。
使用场景:
需要存放1000个学生的学号,安装之前的方式,我们需要定义1000个变量存储,非常麻烦,那么我们可以使用数组进行存储。

5.2 列表的定义与使用

格式:

列表名 = [数据1,数据2,数据3......]
  1. 使用中括号[]进行定义,各项元素之间使用英文逗号分隔。
  2. 列表可以一次性存储多个数据,且可以为不同数据类型。

使用:直接通过 变量名 进行 使用
案例:

ids = [1, 2, 3, 4, 5]
print(ids)  # [1, 2, 3, 4, 5]
print(ids[2])  # 3

图解:

image-20230315154738762

5.3 列表的常用操作

列表的常见操作:增、删、改、查

表1 列表的常见操作

常见操作说明
len(s)计算序列s的长度(元素个数)
min(s)返回序列s中的最小元素
max(s)返回序列s中的最大元素
list.append()在列表list的末尾添加元素x
list.extend()在列表list中添加列表lx的元素,与+=功能相同
list.insert()在列表list索引为i的元素之前插入元素x
listpop()取出并删除列表list中索引为i的元素x
List.remove()删除列表list中第一次出现的元素x
list.reverse()将列表list的元素反转
list.clear()删除列表list中的所有元素
list.copy()生成新列表,并拷贝列表list中的所有元素
list.sort()将列表list中的元素排序

5.3.1 查找

5.3.1.1 下标查找

ids = [1, 2, 3, 4, 5]
print(ids)  # [1, 2, 3, 4, 5]
print(ids[2])  # 3
print(ids[0])  # 1
print(ids[1])  # 2

5.3.1.2 函数查找

  • index():查找指定数据所在位置下标

格式:

列表.index(数据,开始位置,结束位置)
  1. 如果存在多个数据,那么返回是相匹配的第一个数据下标

  2. idnex(数据):如果不知道位置,默认整个列表中查找

案例:

ids = [1, 2, 3, 4, 5]
print(ids.index(4))  # 3
print(ids.index(4, 1, 5))  # 3
print(ids.index(4, 4, 5))  # ValueError: 4 is not in list
print(ids.index(49))  # ValueError: 49 is not in list

注意:如果查找的数据不存在则报错。

  • count():统计指定数据在列表中出现的次数

格式:

列表.count(数据)

案例:

ids = [1, 2, 3, 4, 5]
print(ids.count(4))  # 1
print(ids.count(9))  # 0

注意:如果数据不存在也不会报错

  • len():获取列表的长度(列表中数据的个数)

格式:

len(列表)

案例:

ids = [1, 2, 3, 4, 5]
print(len(ids) ) # 5

5.3.1.3 判断查找

  • in : 判断数据是否列表序列中,如果在返回True,否则返回False

格式:

数据 in 列表

案例:

ids = [1, 2, 3, 4, 5]
print(1 in ids ) # True
print(123 in ids ) # False
  • not in : 判断数据是否列表序列中,如果在返回False,否则返回True

格式:

数据 not in 列表

案例:

ids = [1, 2, 3, 4, 5]
print(1 not in ids ) # False
print(123 not in ids ) # True

5.3.2 增加

增加指定的数据到列表中

  • append():在列表的结尾追加数据

格式:

列表.append(数据)

案例:

ids = [1, 2, 3, 4, 5]
ids.append(89)
print(ids)  # [1, 2, 3, 4, 5, 89]

注意:

如果append()追加的数据是一个序列,则追加整个序列到列表

ids = [1, 2, 3, 4, 5]
nams=["张三","李四"]
ids.append(nams)
print(ids)  # [1, 2, 3, 4, 5, ['张三', '李四']]
  • extend():列表结尾追加数据,如果数据是一个序列,则将这个序列的数据逐一添加到列表。

格式:

列表.extend(数据)

案例:

ids = [1, 2, 3, 4, 5]
ids.extend("4")
ids.extend("9")
nams = ["张三", "李四"]
ids.extend(nams)
print(ids)  # [1, 2, 3, 4, 5, '4', '9', '张三', '李四']
  • insert():在指定位置插入数据。

格式:

列表.insert(位置下标,数据)

案例:

ids = [1, 2, 3, 4, 5]
ids.insert(3, "in")
print(ids)  # [1, 2, 3, 'in', 4, 5]

5.3.3 删除

  • del : 删除列表 | 指定下标数据

格式:

del 列表 | 列表[下标]

案例:

# 删除指定数据
ids = [1, 2, 3, 4, 5]
del ids[2]
print(ids)  # [1, 2, 4, 5]
# 删除整个列表
del ids
print(ids)  # NameError: name 'ids' is not defined

del 删除时不指定下标,会删除整个列表,并释放内存空间

  • pop():删除指定下标的数据(默认为最后一个),并返回该数据。

格式:

列表.pop(下标)

案例:

ids = [1, 2, 3, 4, 5]
# 删除指定下标数据
print(ids.pop(2))  # 3
print(ids)  # [1, 2, 4, 5]
# 不指定下标,默认删除最后一个
print(ids.pop())  # 5
print(ids)
  • remove():删除列表中指定数据的第一个匹配项。

格式:

列表.remove(数据)

案例:

ids = [1, 2, 3, 4, 5]
ids.remove(1)
ids.remove(10)# ValueError: list.remove(x): x not in list
print(ids)

如果删除的数据不存在,就会报错 ValueError: list.remove(x): x not in list

  • clear():清空列表

格式:

列表.clear()

案例:

ids = [1, 2, 3, 4, 5]
ids.clear()
print(ids)  # []

5.3.4 修改

  • 通过下标修改

格式:

列表[下标] = 数据

案例:

ids = [1, 2, 3, 4, 5]
ids[0] = 99
print(ids)  # [99, 2, 3, 4, 5]
  • reverse():倒叙反转

格式:

列表.reverse()

案例:

ids = [1, 2, 3, 4, 5]
ids.reverse()
print(ids)  # [5, 4, 3, 2, 1]
  • sort():排序

格式:

列表.sort(key=None,reverse=True | False )

reverse=True : 倒序(降序) ,reverse=False:正序(升序,默认)

案例:

ids = [6, 0, 1, 99, 3, 4, 5]
ids.sort()
print(ids)  # [0, 1, 3, 4, 5, 6, 99]
ids.sort(reverse=True)
print(ids)  # [99, 6, 5, 4, 3, 1, 0]
ids.sort(reverse=False)
print(ids)  # [0, 1, 3, 4, 5, 6, 99]

5.3.5 复制

  • copy():复制

格式:

列表.copy()

案例:

ids = [1, 2, 3, 4, 5]
new_ids = ids.copy()
print(new_ids)  # [1, 2, 3, 4, 5]

5.4 列表遍历

去获取或者打印列表中的每一个数据

  • for 遍历

案例:

ids = [1, 2, 3, 4, 5]
for i in ids:
    print(i)
  • while 遍历
ids = [1, 2, 3, 4, 5]
i = 0  # i:下标
while i <= len(ids) - 1:
    print(ids[i])
    i += 1

5.5 列表嵌套(多维列表)

列表嵌套相当于其他语言中的多维数据

比如:定义一个年级,年级中有三个班级

案例:

# nj21 = [["张三", "李四", "王二"],["小明", "迪迦"],["彦祖", "冠希", "你"]]
nj21 = []
bj01 = ["张三", "李四", "王二"]
bj02 = ["小明", "迪迦"]
bj03 = ["彦祖", "冠希", "你"]
# 将 班级 放入 年级中
nj21.append(bj01)
nj21.append(bj02)
nj21.append(bj03)
# print(nj21)
# 有一天,有一个塞亚他要插班,要将座位放在迪迦的前面
flag = False  # 定义标志,表示插班成功
for bj in nj21:  # 遍历年级
    for bj_stu in bj:
        if bj_stu == "迪迦":
            dj_index = bj.index(bj_stu)
            print("迪迦的下标:", dj_index)
            bj.insert(dj_index, "塞亚")
            print("塞亚插班成功!正在退出循环")
            # 插班成功,将标志改成 True
            flag = True
            break  # 停止的 内层循环,思考?当插入之后停止所有!
    print(bj)
    # 判断标志,是否插班成功,如果成功,就退出
    if flag == True:
        print("退出成功!")
        break
print("插入的年级信息:", nj21)

5.6 练习

好友信息管理(姓名,性别,联系)
功能:
    查看所有好友信息
    修改指定好友信息
    删除指定好友
    增加好友
    清空好友列表
    退出
user = "root"
pwd = "root"
friends = [
    ["张三", "男", 135897],
    ["李四", "男", 135897],
    ["李四", "男"]
]  # 存储好友

while True:
    in_user = input("请输入用户名:")
    in_pwd = input("请输入密码:")
    # 比较用户名和密码是否一致
    if user == in_user and pwd == in_pwd:
        while True:
            # 登录成功,显示功能面板
            print(10 * "=" + "欢迎使用好友管理系统" + 10 * "=")
            print("""
                1:查看所有好友信息
                2:增加好友
                3:删除指定好友
                4:修改指定好友信息
                5:清空好友列表
                0:退出系统
            """)
            # 让用户选择想要进行的功能
            x = input("请输入想要进行的操作:")
            if x == "1":
                # 查看所有好友信息
                # 判断好友列表是否存在信息
                if len(friends) == 0:
                    print("你现在并没有好朋友!请选择其他操作!")
                else:
                    # 存在好友
                    print("姓名\t\t性别\t\t电话")
                    for i in friends:
                        for j in i:
                            print(j, end="\t\t")
                        print()
            elif x == "2":
                # 增加好友
                name = input("请输入姓名:")
                sex = input("请输入性别:")
                tel = input("请输入电话号码:")
                list = [name, sex, tel]
                # 判断 list 信息是否已经在 friends列表中存在
                if list not in friends:
                    friends.append(list)
                    print(f"{name} 信息增加成功!")
                else:
                    print("好友已经存在,不需要重复增加!")
            elif x == "3":
                # 删除指定好友
                del_name = input("请输入需要删除的好友姓名:")
                del_flag = False  # 定义标志,表示删除好友成功
                for friend in friends:
                    if del_name in friend:
                        friends.remove(friend)  # friends.remove(["张三", "男", 135897])
                        print(f"好友:{del_name} 信息删除成功!")
                        del_flag = True
                        break
                # 判断 del_flag 是否为 True,为 Fasle 表示好友不存在,没有删除
                if del_flag == False:
                    print(f"删除失败!好友:{del_name} 不存在!")
            elif x == "4":
                # 修改指定好友信息
                up_name = input("请输入需要修改信息的好友姓名:")
                up_flag = False  # 定义标志,表示好友不存在,提示信息
                for friend in friends:
                    if up_name in friend:  # friend=["张三", "男", 135897]
                        # 开始修改
                        new_name = input("新的姓名:")
                        new_sex = input("新的性别:")
                        new_tel = input("新的电话:")
                        # 先找到 friend 在 friends列表中的下标
                        index = friends.index(friend)
                        friends[index] = [new_name, new_sex, new_tel]
                        print("信息修改成功!")
                        # 修改成功之后,将up_flag 改为 True ,修改成功
                        up_flag = True
                        break
                # 判断 up_flag ,用于判断修改是否成功
                if up_flag == False:
                    print(f"修改失败!好友:{up_name} 不存在!")
            elif x == "5":
                # 清空好友列表
                while True:
                    sure = input("您确定需要清空所有好友吗?(y/n)")
                    if sure == "y":
                        friends.clear()
                        print("好友列表清空成功!")
                        break
                    elif sure == "n":
                        print("ok!不清空好友列表!")
                        break
                    else:
                        print("您的输入有误!请重新输入!")
            elif x == "0":
                print("欢迎下次使用!彦祖")
                exit(0)
            else:
                print("您输入有误!")
    else:
        print("用户名或密码错误!请重新输入!")
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值