(自学#Python)Day07-熟悉列表存储原理及元组基本操作

本文详细介绍了Python中列表的内存结构、添加、删除、遍历方法,以及浅拷贝与深拷贝的区别。此外,还涵盖了列表连接字符串、字符串拆分、列表推导式、元组的基本操作和列表与元组的比较。
摘要由CSDN通过智能技术生成

(自学Python)Day07-熟悉列表存储原理及元组基本操作

一、列表内存图

1、添加、删除

(1)了解列表添加、删除
"""
    列表内存图
        添加
        删除
"""
list_name = ["周杰伦"]
list_name.append("毛不易")
list_name.insert(0, "李健")

list_name = ["李健", "周杰伦", "毛不易"]
del list_name[0]
list_name.remove("毛不易")

(2)练习列表添加、删除
"""
    画出下列代码内存图
"""
list01 = ["北京", "上海", "深圳"]
# 传递的是列表地址(一份列表)
list02 = list01
# 旧数据向后移动
list01.insert(0, "天津")
# 数据向前移动
del list01[1]
print(list02)  # 互相影响

2、遍历

(1)了解列表遍历
"""
    列表内存图
        遍历
"""
list_name = ["李健", "周杰伦", "毛不易"]
# 读取全部元素
for item in list_name:
    print(item)
    # item = ""# 修改的是item,与列表无关

# 修改全部元素
for i in range(len(list_name)): # 0 1 2
    list_name[i] = ""

(2)练习列表遍历
"""
	列表读和修改的规范
"""
list01 = [1, 9, 8, 6, 0, 8, 6, 3, 3, 4]
# 读取全部元素
for item in list01:
    if item < 5:
        print(item)

# 修改全部元素
for i in range(len(list01)):
    if list01[i] < 5:
        list01[i] = 5

# "特别讨厌的人"
# for i in list01:
# for item in range(len(list01)):

3、深浅拷贝

(1)了解列表深浅拷贝
"""
    深浅拷贝
        拷贝:复制/备份的过程,防止数据意外破坏
        浅拷贝:复制第一层数据,共享深层数据
            优点:占用内存较小
            缺点:当深层数据被修改时,互相影响
            适用性:优先
        深拷贝:复制所有层数据
            优点:绝对互不影响
            缺点:占用内存较大
            适用性:深层数据会被修改
"""
list_name = ["李健", ["周杰伦", "毛不易"]]
data01 = list_name[:]  # 触发浅拷贝
data01[0] = "贱贱"  # 修改第一层(2份),互不影响
data01[1][0] = "杰伦"  # 修改深层(1份),互相影响
print(list_name)

# 准备深拷贝工具
import copy

list_name = ["李健", ["周杰伦", "毛不易"]]
data01 = copy.deepcopy(list_name)# 执行深拷贝
data01[0] = "贱贱"  # 修改第一层(2份),互不影响
data01[1][0] = "杰伦"  # 修改深层(2份),互不影响
print(list_name)


在这里插入图片描述

(2)练习列表深浅拷贝
"""
    画出下列代码内存图
"""
import copy

list01 = ["北京", ["上海", "深圳"]]
# 赋值:传递列表地址(1份)
list02 = list01
# 浅拷贝:复制第一层(2份),共享深层(1份)
list03 = list01[:]
# 深拷贝:复制所有层(2份)
list04 = copy.deepcopy(list01)
# 互不影响
list04[0] = "北京04"
list04[1][1] = "深圳04"
print(list01)  # ?
# 互相影响
list02[0] = "北京02"
list02[1][1] = "深圳02"
print(list01)  # ?
# 修改第一层,互不影响
list03[0] = "北京03"
# 修改深层,互相影响
list03[1][0] = "上海03"
print(list01)  # ?

二、列表 连接字符串

1、了解列表 连接字符串

"""
    列表 -连接-> 字符串
"""
list01 = ["a", "b", "c"]
result = "-".join(list01)
print(result)  # a-b-c

# 面试:根据xx条件,循环拼接字符串
# 需求: range(10)   0123456789
# str_result = ""
# for number in range(10):
#     # "" + "0"
#     # "0" + "1"
#     # "01" + "2"
#     # "012" + "3"
#     # 缺点:每次循环相加时都会产生新数据,替换旧数据
#     str_result += str(number)
# print(str_result)

# 解决:利用可变数据代替不可变数据
#         列表        字符串
list_result = []
for number in range(10):
    list_result.append(str(number))
result = "".join(list_result)  # ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
print(result)

2、练习列表 连接字符串

"""
    练习:
    在终端中,循环录入字符串,如果录入空则停止.
    停止录入后打印所有内容(一个字符串)
"""
list_result = []
while True:
    content = input("请输入内容:")
    if content == "":
        break
    list_result.append(content)
str_result = "_".join(list_result)
print(str_result)

三、字符串拆分列表

1、了解字符串拆分列表

"""
    字符串 -拆分-> 列表
"""
# 使用一个字符串存储多个信息
list_result = "唐僧,孙悟空,八戒".split(",")
print(list_result) # ['唐僧', '孙悟空', '八戒']

# 练习:将下列英文语句按照单词进行翻转.
# 转换前:To have a government that is of people by people for people

2、练习字符串拆分列表

"""
   练习:将下列英文语句按照单词进行翻转.
   转换前:To have a government that is of people by people for people
   转换后:people for people by people of is that government a have To
"""
sentence = "To have a government that is of people by people for people"
list_temp = sentence.split(" ")
str_result = " ".join(list_temp[::-1])
print(str_result)

四、列表推导式

1、了解列表推导式

"""
    列表推导式
        根据其他容器,以简易方式构建新列表
"""
list01 = [4, 3, 4, 45, 6, 7, 8]
# 需求:找到所有小于10的数字,存入新列表
# list_new = []
# for item in list01:
#     if item < 10:
#         list_new.append(item)
# print(list_new)

list_new = [item for item in list01 if item < 10]
print(list_new)

# list_new = []
# for item in list01:
#     list_new.append(item ** 2)
# print(list_new)
list_new = [item ** 2 for item in list01]
print(list_new)

2、练习列表推导式

"""
	练习:
    生成10--30之间能被3或者5整除的数字
    [10, 12, 15, 18, 20, 21, 24, 25, 27]

    生成5 -- 20之间的数字平方
    [25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361]
"""
# list_result = []
# for number in range(10, 31):
#     if number % 3 == 0 or number % 5 == 0:
#         list_result.append(number)
# print(list_result)

list_result = [number for number in range(10, 31) if number % 3 == 0 or number % 5 == 0]
print(list_result)

list_result = [item ** 2 for item in range(5, 21)]
print(list_result)

五、元组基本操作

"""
    元组
        创建
        定位
        遍历
"""
# 1. 创建
tuple_name = ("李健", "周杰伦", "毛不易")
list01 = ["李健", "周杰伦"]
tuple02 = tuple(list01)

# 2.定位
print(tuple_name[1])
print(tuple_name[:2])

# 3.遍历
for item in tuple_name:
    if len(item) == 3:
        print(item)

# 4.在没有歧义的情况下,可以省略小括号
tuple03 = 10, 20, 30
print(tuple03)

# 5.元组中如果只有一个元素,必须添加逗号
tuple04 = ("李健",)
print(tuple04)
# 特别小心:下列代码是元组,不是字符串(因为有逗号)
name = "李健",
print(name)

# 6.序列拆包
a, b, c = tuple_name
a, b, c = [10, 20, 30]
a, b, c = "孙悟空"
print(a)
print(b)
print(c)

# 变量交换
a = 10
b = 20
a, b = b, a

六、元组与列表的区别

"""
    画出下列代码内存图
"""
name = "张无忌"
names = ["赵敏", "周芷若"]
tuple01 = ("张翠山", name, names)
name = "无忌哥哥"
tuple01[2][0] = "敏儿"
print(tuple01)  # ?

"""
    以容器思想改造下列代码
        统一管理数据
"""
# month = int(input("请输入月份:"))
# if 1 <= month <= 12:
#     if month == 2:
#         print("29天")
#     elif month == 4 or month == 6 or month == 9 or month == 11:
#         print("30天")
#     else:
#         print("31天")
# else:
#     print("月份输入有误")


# month = int(input("请输入月份:"))
# if 1 <= month <= 12:
#     if month == 2:
#         print("29天")
#     elif month in (4,6 ,9, 11):
#         print("30天")
#     else:
#         print("31天")
# else:
#     print("月份输入有误")

tuple_days = (31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
print(tuple_days[0])
print(tuple_days[1])
month = int(input("请输入月份:"))
print(tuple_days[month - 1])
print(tuple_days[:3])
# 根据月日,计算是这一年的第几天.
# 公式:前几个月总天数 + 当月天数
# 例如:5月10日
# 计算:31 29 31 30 + 10
tuple_day = (31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
month = int(input("请输入月:"))  # 3
day = int(input("请输入日:"))  # 15
# 因为tuple_day[:2]会触发浅拷贝,
# total_day = 0
# for item in tuple_day[:2]:
#     total_day += item

# 所以建议使用range()
# total_day = 0
# for i in range(2):
#     total_day += tuple_day[i]

# 最简洁
# total_day = sum(tuple_day[:2])
total_day = sum(tuple_day[:month - 1])
total_day += day
print(total_day)
"""
    画出下列代码内存图
"""
list01 = [10, 20, 30]
for item in list01:
    item += 1	#修改的变量item,列表没有变化
print(list01)  # ?

list01 = [10, 20, 30]
fori in range(len(list01)): #0 1 2
    list01[i] += 1
print(list01) # ?

list02 = [
    [10],
    [20],
    [30],
]
for item in list02:
    item[0] += 1
print(list02)  # ?

七、练习

"""
    将列表中的数字累乘
        list02 = [5, 1, 4, 6, 7, 4, 6, 8, 5]
    结果:806400
"""

list02 = [5, 1, 4, 6, 7, 4, 6, 8, 5]
result = 1  # 因为1乘以任何数字,都不改变.
for item in list02:
    result *= item
print(result)
"""
    在终端中录入疫情地区名称,如果输入空字符串,则停止。
    如果录入的名称已经存在不要再次添加.
    最后打印所有省份名称(一行一个)
"""
list_regions = []
while True:
    region = input("请输入疫情地区名称:")
    if region == "":
        break
    if region in list_regions:
        print("已经存在")
    else:
        list_regions.append(region)

for item in list_regions:
    print(item)
"""
    在终端中录入3个疫情省份的确诊人数
    最后打印最大值、最小值、平均值.(使用内置函数实现)
"""
# list_confirmed_num = []
# for i in range(3):  # 0  1  2
#     # confirmed_num = int(input("请输入第%s个确诊人数:" % (i + 1)))
#     confirmed_num = int(input(f"请输入第{i + 1}个确诊人数:"))
#     list_confirmed_num.append(confirmed_num)

list_confirmed_num = [int(input(f"请输入第{i + 1}个确诊人数:")) for i in range(3)]

print(max(list_confirmed_num))
print(min(list_confirmed_num))
print(sum(list_confirmed_num) / len(list_confirmed_num))
"""
    根据列表中的数字,重复生成*.
        list01 = [1, 2, 3, 4, 5, 4, 3, 2, 1]
    效果:
        *
        **
        ***
        ****
        *****
        ****
        ***
        **
        *
"""
list01 = [1, 2, 3, 4, 5, 4, 3, 2, 1]

# 读取全部元素
for item in list01:
    print("*" * item)  # 打印列表元素

# 更擅长修改全部元素
# for i in range(len(list01)):
#     print("*" * list01[i])

# 从第二个元素开始读取剩下元素
# for item in list01[1:]: # 会触发浅拷贝,不建议
#     print("*" * item)

for i in range(1, len(list01)):
    print(list01[i])
  • 12
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值