Python3基础

目录

一、入门

1.1 编辑器

1.2 扩展工具

1.3 Python是怎么运行的

二、基本类型

2.1 字符串

2.1.1 字符串长度 len(str)

2.1.2 获取指定位置的字符

2.1.3 切片

2.1.4 字符串拼接

2.1.5 字符串大小写转换

2.1.6 strip() lstrip() rstrip()

2.1.7 str.count(str1)

2.1.8 find()  index() 查找子字符串

2.1.9 replace(old, new) 字符串替换

2.1.10 split()  字符串分割

2.1.11 字符串遍历

2.2 number 

2.2.1 数据类型介绍和算术运算符

2.2.2 数字的相关方法

2.3 bool类型

2.4 字符串格式化

2.4.1 方式一

2.4.2 方式二

三、控制流

3.1 if 语句

3.3 循环

3.2.1 for循环

3.2.2 while循环

3.3 无限循环

四、方法functions

4.1 方法声明和调用

4.2 含参数的方法

4.3 方法的类型

4.3.1 执行指定功能

4.3.2 返回计算结果

4.4 方法的参数

4.4.1 位置参数

4.4.2 关键字参数

4.4.3 缺省参数

4.4.3 不定长参数

4.5 方法内变量的生效范围

4.6 匿名函数

4.6.1 函数作为参数传递

4.6.2 lambda匿名函数

五、数据结构

5.1 list 列表

5.1.1 定义列表

5.1.2 获取列表指定下标内容

5.1.3 列表的切片

5.1.3 把列表内元素赋值给多个变量

5.1.4 列表内循环

5.1.5 插入/删除列表元素

1、append(value) 在列表尾部插入数据

2、insert(i, value)在指定下标插入数据

3、pop() 删除列表末尾的数据

 4、pop(i) 删除指定下标数据

5、remove(value) 删除指定数据

6、del 删除指定下标数据

7、clear() 清空列表

5.1.6 index() 查找指定数据在列表中的下标

5.1.7 count(value) 获取指定数据在列表中出现的次数

5.1.8 sort() 列表数据排序

1、sort() 升序

2、sort(reverse=Ture) 降序

3、sorted(list)升序

4、sorted(list, reverse=Ture)降序

5、 lambda方法

5.1.9 列表遍历

1、while循环遍历

 2、for 循环遍历

5.1.10 map()映射列表数据 

5.1.11 filter() 过滤列表数据

5.1.12 zip()组合多个列表

5.1.13 扩展

1、堆栈

2、队列

5.2 tuple 元组

5.2.1 元组的定义

5.2.2 元组合并

5.3 集合

5.3.1 集合定义

5.3.2 add(value) 添加元素

5.3.3 删除元素

5.3.4 len(set) 获取集合长度

5.3.5 clear() 清空集合

5.3.6 获取多个集合的并集

5.3.7 获取多个集合的交集

5.3.8 获取集合的差集

5.3.9 获取多个集合的对称性差异

5.3.10 集合内部数据的无序性

5.3.11 集合遍历

5.4 dictionary 字典

5.4.1 定义字典

5.4.2 添加元素

5.4.3 修改元素

5.4.4 获取指定key的value

5.4.5  删除指定元素

5.4.6 清空字典

5.4.7 获取字典全部key

5.4.8 获取字典的元素

5.4.9 字典应用于循环

5.5 生成器对象

5.6 解包操作

5.6.1 多个列表合并

5.6.2 多个字典合并

5.7 字符串

5.8 练习

六、文件操作

6.1 文件读取

6.1.1 open() 打开文件

6.1.2 read()读取文件内容

6.1.3 readlines()读取文件 

6.1.4 readline()读取文件 

6.1.5 使用for循环读取文件 

6.1.6 关闭文件连接 

6.1.7 使用with open打开文件 

6.2 文件写入

正则匹配

1. 匹配单个字符

2. 匹配多个字符

3. 匹配开头和结尾

4. 匹配分组

5. 匹配转义字符

七、异常exceptions

7.1 捕获异常

7.2 捕获多个异常

7.3 异常的else和finally语句

7.3.1 在try模块连接资源在finally模块关闭资源

7.3.2 使用with语句自动释放资源

7.4 异常具有传递性

7.5 抛出异常

八、类classes

8.1 类定义

8.2 构造函数

8.3 类和实例属性

8.3.1 实例属性

8.3.2 类属性

8.4 类和实例方法

8.4.1 实例方法

8.4.2 类方法

8.5 magic methods魔术方法

8.5.1 __str__

8.5.2 比较对象大小的魔法方法

8.5.3 对象进行算术运算的魔法方法

8.5.4  自定义的magic method

8.6 python的私有成员

8.7 类属性property

8.7.1 使用property()方法创建类属性

8.7.2 装饰器@property 创建类属性

8.8 继承inheritance

8.8.1 单继承和多层继承

1. 单继承

2.  多层继承

3. isinstance(instance, class)

4. issubclass(sub, base)

5.  重写父类方法/属性

子类重写父类同名方法

子类调用父类同名方法

8.8.2 多继承

1、 多继承--查看子类继承父类的继承顺序

2、多继承--调用父类同名方法

默认调用情况

子类调用父类同名方法

8.8.3 私有和继承

 8.8.4 多态

8.8.5 抽象基类

8.8.6 类型注解

1、变量的类型注解

2、函数和方法的类型注解

3、Union联合类型 注解

8.8.7 属性类

九、模块和包

9.1 模块

9.1.1 模块的导入和使用

 9.1.2 自定义模块

 9.2 包

9.2.1 自定义包

9.2.2 第三方包

9.3 练习

9.3.1 疫情确诊人数走势折线图

1、json数据格式

2、pyecharts模块介绍

3、pyecharts快速入门

4、数据处理

5、创建折线图

9.3.2 疫情地图绘制

1、基础地图使用

2、全国疫情地图

3、省级疫情地图

9.3.3 柱状图绘制

1、基础柱状图绘制

2、基础时间线柱状图

3、GDP动态柱状图绘制

十、python的标准库

10.1 pathlib

10.1.1 创建目录对象

10.1.2 目录对象的相关操作

10.1.3 目录对象的使用

1、path.iterdir()

2、path.glob("匹配模式")

3、path.rglob("匹配模式")


一、入门

1.1 编辑器

编辑器:vscode

1.2 扩展工具

语法检查工具pylint

 点击install即可

 确认下当前使用的Python版本是不是3以上,之后点击install即可

如果代码有错误,代码行会飘红,点击View—— Problems(shift+ctrl+M)打开报错的详细信息框

命令策略面板Command Palette(shift+ctrl+P) ,输入linter

点击select linter

pylint 是最受欢迎和vscode中默认的语法检查工具

代码格式化工具pep8

PEP 8 – Style Guide for Python Code | peps.python.org

命令策略面板Command Palette(shift+ctrl+P),打开面板输入format

 

最受欢迎和默认的代码格式化工具是autopep8,点击Yes即可安装pep8工具

再次打开命令策略面板Command Palette(shift+ctrl+P),输入format点击format document命令就可以对当前代码文件进行格式化。

可以对格式化时机进行设置,不能每次都要执行format document命令,设置操作如下:

这样当你保存文件时会自动完成格式化校验和修正。

代码运行扩展工具:code runner

 点击install

以后需要运行代码时不需要输入Python xx.py,ctrl+alt+N(ios是Ctrl+option+N)即可

1.3 Python是怎么运行的

二、基本类型

number:int  和 float

boolean:True    False

string:"Python Programming"

字符串中有特殊字符,如单引号 双引号 反斜杠等需要输出时,使用转义字符\即可

course = "Python \''Programming"

course = "Python \'Programming"

course = "Python \\Programming"

变量命名按照驼峰

2.1 字符串

2.1.1 字符串长度 len(str)

len()为Python内置函数,并非字符串特有

course = "Python Programming"

str_len = len(course)

2.1.2 获取指定位置的字符

获取数据指定下标指的方法是通用的,对列表  字典  

course = "Python Programming"

# 获取下标0对应的字符

print(course[0])

# 获取字符串的最后一个字符
print(course[-1])
print(course[17])

2.1.3 切片

注意:切片可以得到一个全新的字符串,它有单独的存储地址,原来的父字符串不会有任何改变

course = "Python Programming"
# 获取course字符串从下标0开始到下标3,但不包含下标3对应字符的一段字符串------即Pyt
print(course[0:3])
print(course[:3])
# 注意切片不会影响course字符串本身

# 获取course字符串从下标3开始一直到末尾的一段字符串
# -----即hon Programming
print(course[3:])

# 获取course字符串从下标0开始,到下标8为止(不包括下标8对应字符),没3个取1个
# 下标0~下标8对应Python Pr,不包含8,则为Python P
# 取下标0 对应的P
# 向后数3个yth,3个取1个,取h
# 再向后数3个on ,3个取1个,取空格
# 再向后数只有1个字符P,所以不能继续
# 所以最后得到的是Ph 
print(course[0:8:3])


# 复制一个和course字符串完全一样的子字符串,但对新字符串的改动不能影响到course字符串本身
new_str = course[:]
print(new_str)
# 注意不能使用赋值 new_str = course,因为course和new_str这样的变量名其实只是一个指针,指向的内存地址,该地址内存储的内容是字符串内容,使用赋值会导致 new_str 和 course 指向的是同一个内存地址

2.1.4 字符串拼接

方法一:sum_str = str1 + " " + str2

方法二:sum_str = f"{str1} {str2}"

# 字符串拼接
first = "John"
last = "Smith"
full_name = f"{first} {last}"
print(full_name)

2.1.5 字符串大小写转换

str.upper()  ——字符串str全部变为大写

str.lower() ——字符串str全部变为小写

str.title() —— 字符串内单词的首字母都变为大写

原始字符串str在经过对应方法处理后得到的是一个新的字符串,存储在新的地址

原始字符串str没有任何改变

course = "python programming"
print("新的字符串是:", course.title())
print("原始字符串course是:", course)

2.1.6 strip() lstrip() rstrip()

不传参数就是去除空格和换行符

传参数就是去除指定字符串

str.strip() —— 去除字符串左右两侧多余的空格

str.lstrip() —— 去除字符串左侧多余的空格

str.rstrip() —— 去除字符串右侧多余的空格

slogen = "12I like learning21"
new_str = slogen.strip("12")
print(new_str)  # I like learning
# 把“12”看成2个字符串“1”  和  “2”
# 所以slogen左右的12 21 都会被去除
course = "      python programming      "
print(course.strip())

2.1.7 str.count(str1)

计算子串str1在字符串中出现的次数

2.1.8 find()  index() 查找子字符串

str.find(str1) —— 在str字符串中查找str1,如果找到了,就返回第一次匹配时对应的下标

如果没找到就返回-1

str.index(str1)—— 在str字符串中查找str1,如果找到了,就返回第一次匹配时对应的下标

如果没找到就返回ValueError

course = "python programming"
print(course.find("p"))
# 返回0
print(course.find("H"))
# 返回-1
print(course.find("pro"))
# 返回7


course = "python programming"
value = course.index("pro")
print(value)  # 7
value2 = course.index("p")
print(value2)   # 0
value3 = course.index("P")
# print(value3)    # ValueError: substring not found

2.1.9 replace(old, new) 字符串替换

str.replace(oldStr, newStr) —— 用newStr 替换字符串str中的oldStr

course = "python programming"
print(course.replace("p", "hhhh"))
# 返回hhhhython hhhhrogramming

2.1.10 split()  字符串分割

slogen = "I like learning"
arr = slogen.split(" ")
print(arr)  # ['I', 'like', 'learning']

str1 in str 判断str1是否是str的子字符串,是就返回True,不是就返回False

str1 not in str

course = "python programming"
print("pro" in course)


2.1.11 字符串遍历

2.2 number 

2.2.1 数据类型介绍和算术运算符

整数   小数  复数a+bi

算数运算符:加+    减-     乘*    除尽/     除后取整//      除后取余%      取幂**

+=     -=      *=     /=     //=      %=      **=

print(10 + 3)
# 13
print(10 - 3)
# 7
print(10 * 3)
# 30
print(10 / 3)
# 3.3333333333333335
print(10 // 3)
# 3
print(10 % 3)
# 1
print(10 ** 3)
# 1000
x = 10
# x += 3
# x -= 3
# x *= 3
# x /= 3
# x //= 3
# x %= 3
x **= 3
print(x)

2.2.2 数字的相关方法

可以参考:math — Mathematical functions — Python 3.11.4 documentationPython3.9标准库math中的函数汇总介绍(53个函数和5个常数)_python的math库中的函数有哪些_昊虹AI笔记的博客-优快云博客

round(num) —— 四舍五入取整

print(round(2.1))
# 2
print(round(2.6))
# 3

abs(num) —— 取num的绝对值

print(abs(-7.5))
# 7.5
print(abs(0))
# 0

导入数学模块 import math

math.ceil(num) —— 向上舍入到最接近的整数

import math

print(math.ceil(2.2))
# 3

input()获取用户输入内容以字符串形式存储,所以需要注意数据处理时进行类型转换。

x = input("x: ")

print(type(x))

y = int(x) ** 2

# 表准字符串输出print(f"")

print(f"x: {x}, y: {y}")

类型转换的方法有:

int(x)

float(x)

bool(x)

str(x)

2.3 bool类型

print(bool(0))

#  返回false

print(bool(''"))

# 返回false

2.4 字符串格式化

2.4.1 方式一

在字符串内(即引号内)使用%s   %d    %f  进行占位,后面使用按照占位顺序传入变量,并放在%()的括号内

 

 

2.4.2 方式二

快速字符串格式化:

f"ababbajajaik{变量名}"

这种方式不关心变量类型,同样也不会做变量精度的控制。

 

 

三、控制流

3.1 if 语句

if 条件1:

        balabala

elif 条件2:

        balabal

.

.

.

elif 条件n:

        balabala

else:

        如果以上条件判断都不满足,执行这里的逻辑

逻辑运算符and   or    not 可以在条件表达式中使用

 random.random(): 返回随机生成的一个浮点数,范围在[0,1)之间

random.uniform(a, b): 返回随机生成的一个浮点数,范围在[a, b)之间

random.randint(a,b):生成指定范围内的整数 

random.randint(0,100) 就是随机生成一个0~100的数,包括0和100

np.random.randint(0,10)  和上面作用一样, 左闭右开,包括0 不包括10

3.3 循环

3.2.1 for循环

for number in range(3):

# range(3)取值范围[0, 3) 即0  1  2

# range(1, 4)取值范围[1, 4) 即1  2  3

# range(1, 10, 2)  取值[1, 10) 且时隔1个数字取一个  即1   3   5   7   9

        print("hello", number)

# 99乘法表
for row in range(1, 10):
    for col in range(1, row+1):
        print(f"{col} * {row} = {col * row}\t",end='')
        # 在print方法里使用end=''实现不换行
    # 一行结束时需要换行
    print()

输出内容但是不换行:print(f"要输出的内容", end='')

3.2.2 while循环

while 条件表达式:

        balabala

row = 1
while row < 10:
    col = 1
    while col <= row:
        print(f"{col} * {row} = {col * row}\t", end='')
        col += 1
    print()
    row += 1

3.3 无限循环

就是for或者while后面的条件永远是Ture,这个时候在循环体内需要设置其他判断,当满足这个判断时用break结束循环。

四、方法functions

4.1 方法声明和调用

def test():

        balkabala

test()

4.2 含参数的方法

def test(参数1, 参数2, ...参数n):

        balabal

hh 

test(参数值1, 参数值2, ...参数值n)

4.3 方法的类型

4.3.1 执行指定功能

def greet(name):

        print(f"hi {name}")

#执行完任务后,可能会把结果输出在终端或者什么也不输出

greet("mosh")

# 函数没有设置返回值时,python默认会返回None

 函数说明文档:

4.3.2 返回计算结果

def get_greeting(name):

        reurn f"hi {name}"

# 方法执行完后会返回结果

message = get_greeting("mosh")

方法可以有多个返回值,并且可以使用多个变量接收函数的返回值

 

4.4 方法的参数

4.4.1 位置参数

4.4.2 关键字参数

 

4.4.3 缺省参数

def test(teacher, course = "python"):

    return f"{teacher} 负责 {course}"

test("mosh")

4.4.3 不定长参数

# 定义可变参数

def test(*numbers):
        print(numbers)

        # 元组可以用于循环

        sum = 0

        for number in numbers:

                sum += number

        return sum

# 调用方法传递多个数据时,这些数据存储在  元组中

# 元组中的元素是不允许修改和删除的,只能增加,如果非要删除只能把整个元组都删了

test(1, 2, 3, 4)

# 得到的是元组:(1, 2, 3, 4)

def save_user(**user):

    print(user)

    print(user["name"])

# 带2个*号的参数会存储在字典中  {key1 : value1, key2 : value2 },可以通过key访问字典内部的值

save_user(id = 1, name = "john", age = 22)

# 得到的是字典: {'id': 1, 'name': 'john', 'age': 22}

4.5 方法内变量的生效范围

定义在方法内部的变量是局部变量,生命周期仅限于方法内。

全局变量定义在方法外,在整个python文件都是生效的,除非必要尽量不要定义全局变量。

局部变量可以和全局变量同名,但最好不要这样做。

还有不要在方法内修改全局变量,容易把业务逻辑改坏。

message = "b"

def greet(name):

    # global message 在方法内部使用全局变量,后面可以用message = "hello"随意修改全局变量的值,但是最好别修改

    message = "a" # 可以定义局部变量名和全局变量同名   但是最好不要这样做

    print(message)

greet("mosh") # 里面使用的是局部变量 打印"a"

print(message) # 打印的是全局变量 "b"

4.6 匿名函数

4.6.1 函数作为参数传递

4.6.2 lambda匿名函数

五、数据结构

5.1 list 列表

5.1.1 定义列表


# 定义列表
letters = ["a", "b", "c"]
# 列表内嵌套列表
matrix = [[0, 1], [2, 3]]
# 初始化一个含有100个0元素的列表
zeros = [0] * 100
print(zeros)
# 列表组合
combined = letters + matrix
print(combined)
# ['a', 'b', 'c', [0, 1], [2, 3]]
# 使用list()方法创建列表
numbers = list(range(3, 20, 2))
print(numbers)
# [3, 5, 7, 9, 11, 13, 15, 17, 19]
greet = list("hello mosh")
print(greet)
#  ['h', 'e', 'l', 'l', 'o', ' ', 'm', 'o', 's', 'h']
print(len(greet))
#  10

5.1.2 获取列表指定下标内容

letters = ["a", "b", "c","d"]
# 获取列表指定下标的内容
print(letters[1]) 
#  b
print(letters[-1])
#  d
# 修改列表指定下标的值
letters[0] = "A"
print(letters)
# ['A', 'b', 'c', 'd']

5.1.3 列表的切片

letters = ["a", "b", "c","d"]
#  获取列表的一段数据作为新列表的内容

# new_letters = letters[0:3]
new_letters = letters[:3]
print(new_letters)
#  ['A', 'b', 'c']

# new_letters = letters[0:]
# new_letters = letters[:4]
new_letters = letters[:]
print(new_letters)
#  ['A', 'b', 'c', 'd']


new_letters = letters[::2]
print(new_letters)
#  ['A', 'c']


print(letters)
#  ['A', 'b', 'c', 'd']
numbers = list(range(20))
# 取偶数
new_numbers = numbers[::2]
print(new_numbers)
#  [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

#  列表逆序
new_numbers = numbers[::-1]
print(new_numbers)
#  [19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

print(numbers)
#  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

5.1.3 把列表内元素赋值给多个变量

需要注意的是变量的个数和列表内元素个数要一致,或者使用可变数量的变量接收剩余列表元素

numbers = [1, 2, 3]
first, second, third = numbers
print(f"first = {first} second = {second} third = {third}")
# first = 1 second = 2 third = 3
numbers = [1, 2, 3, 4, 5, 6]
#  使用可变数量的变量third接收列表剩余元素
first, second, *third = numbers
#  赋值的时候third前面只能有一个星号
print(f"first = {first} second = {second} third = {third}")
#  first = 1 second = 2 third = [3, 4, 5, 6]
#  注意:接收列表剩余多个元素的third也是一个列表
numbers = [1, 2, 3, 4, 5, 6]
# 如果只需要用到列表的第一个和最后一个元素
first, *others, last = numbers
print(f"first = {first} others = {others} last = {last}")
# first = 1 others = [2, 3, 4, 5] last = 6

5.1.4 列表内循环

# 列表用于循环体
letters = ["a", "b", "c"]
for letter in letters:
    print(letter)
# a
# b
# c

# 获取列表元素的同时打印元素的下标
for index, letter in enumerate(letters):
    print(f"index = {index} letter = {letter}")
# index = 0 letter = a
# index = 1 letter = b
# index = 2 letter = c

5.1.5 插入/删除列表元素

1、append(value) 在列表尾部插入数据

list.append(value)

letters = ["a", "b", "c"]
letters.append("d")
print(letters)
# ['a', 'b', 'c', 'd']
2、insert(i, value)在指定下标插入数据

list.insert(i, value)

letters.insert(1, "f")
print(letters)
# ['a', 'f', 'b', 'c', 'd']
3、pop() 删除列表末尾的数据

list.pop()     pop()方法会把移除的数据元素返回

letters = ['a', 'f', 'b', 'c', 'd']
c = letters.pop()
print(c)   # d
print(letters)  # ['a', 'f', 'b', 'c']
 4、pop(i) 删除指定下标数据

list.pop(i)

letters = ['a', 'f', 'b', 'c', 'd']
c = letters.pop(1)
print(c)   #  f
print(letters)  # ['a', 'b', 'c', 'd']
5、remove(value) 删除指定数据

list.remove(value) 只会把列表中第一个匹配的数据删除,如果列表中有重复数据,剩余的数据会保留

letters =["a", "b", "c", "d", "b"]
letters.remove("b")
print(letters)
# ['a', 'c', 'd', 'b']
6、del 删除指定下标数据

del list[i]  删除指定下标的元素

letters =["a", "b", "c", "d", "b"]
del letters[1]
print(letters)
# ['a', 'c', 'd', 'b']

del list[n:m]  删除下标n到下标m-1对应的元素值    n < m


letters =["a", "b", "c", "d", "b"]
# 删除列表内连续几个数据
del letters[0:2]
# 删除的是下标0  1对应的数据,不包括下标2的数据
print(letters)
# ['c', 'd', 'b']
7、clear() 清空列表

list.clear() 

letters =["a", "b", "c", "d", "b"]
letters.clear()
print(letters)
# []

5.1.6 index() 查找指定数据在列表中的下标

index("目标值") 只会返回从左匹配的第一个匹配成功的数据下标

如果查找的数据在列表中没有则会报ValueError

letters =["a", "b", "c", "d", "b"]
print(letters.index("b"))
# 1
print(letters.index("f"))
# ValueError: 'f' is not in list

为了避免因为查找额数据在列表中不存在导致的报错,可以加上if判断


letters =["a", "b", "c", "d", "b"]
if "b" in letters:
    print(letters.index("b"))
    # 1
if "f" in letters:
    print(letters.index("f"))

5.1.7 count(value) 获取指定数据在列表中出现的次数

count(value) 统计指定元素值在列表中出现的次数

如果给定的元素值在列表中不存在,则返回0

letters =["a", "b", "c", "d", "b"]
print(letters.count("b"))
#  2
print(letters.count("f"))
#  0

5.1.8 sort() 列表数据排序

1、sort() 升序

list.sort() 列表升序排列,不会另存排序结果是直接改变原列表的排序方式

numbers = [3, 51, 2, 8, 6]
numbers.sort()
print(numbers)
# [2, 3, 6, 8, 51]
2、sort(reverse=Ture) 降序

list.sort(reverse=Ture)  列表降序排列,不会另存排序结果是直接改变原列表的排序方式

numbers = [3, 51, 2, 8, 6]
numbers.sort(reverse=True)
print(numbers)
# [51, 8, 6, 3, 2]
3、sorted(list)升序

new_list = sorted(list) 新排序后另存为新的列表,原列表不改变

numbers = [3, 51, 2, 8, 6]
new_numbers = sorted(numbers)
print(new_numbers)
# [2, 3, 6, 8, 51]
print(numbers)
# [3, 51, 2, 8, 6]

4、sorted(list, reverse=Ture)降序

new_list = sorted(list, reverse=Ture) 新排序后另存为新的列表,原列表不改变

numbers = [3, 51, 2, 8, 6]
new_numbers = sorted(numbers, reverse=True)
print(new_numbers)
# [51, 8, 6, 3, 2]
print(numbers)
# [3, 51, 2, 8, 6]

5、 lambda方法
items = [
    ("prodct1", 10),
    ("prodct2", 9),
    ("prodct3", 12)
]

items.sort()
print(items)
# [('prodct1', 10), ('prodct2', 9), ('prodct3', 12)]
# 列表内元素是元组,无法排序

# 自定义排序方法
def sort_item(item):
    return item[1]
    # 返回商品的价格


items.sort(key=sort_item)
# 按照商品的价格进行升序
print(items)
# [('prodct2', 9), ('prodct1', 10), ('prodct3', 12)]

key=lambda parameters:expression 

# items.sort(key=lambda parameters:expression)
items.sort(key=lambda item:item[1])so

items = [
    ("prodct1", 10),
    ("prodct2", 9),
    ("prodct3", 12)
]


# 可以使用lambda表达式  替换上面定义的sort_item方法,可读性会更好
# items.sort(key=lambda parameters:expression)
items.sort(key=lambda item:item[1])
print(items)
# [('prodct2', 9), ('prodct1', 10), ('prodct3', 12)]

5.1.9 列表遍历

1、while循环遍历

 2、for 循环遍历

 

5.1.10 map()映射列表数据 

prices = list(map(lambda item: item[1], items))
# map的语义表达式为:item[1] for item in items

items = [
    ("prodct1", 10),
    ("prodct2", 9),
    ("prodct3", 12)
]
prices = []
for item in items:
    prices.append(item[1])

print(prices)
# [10, 9, 12]


# 使用map方法简单实现上述功能
prices = list(map(lambda item: item[1], items))
# map的语义表达式为:item[1] for item in items
# prices = [item[1] for item in items]
print(prices)

5.1.11 filter() 过滤列表数据

filtered = list(filter(lambda item: item[1] >= 10, items))
# filter方法的语义表达式为:item for item in items if item[1]>=10

items = [
    ("prodct1", 10),
    ("prodct2", 9),
    ("prodct3", 12)
]

filtered = list(filter(lambda item: item[1] >= 10, items))
# filter方法的语义表达式为:item for item in items if item[1]>=10
# filtered = [item for item in items if item[1]>=10]
print(filtered)
# [('prodct1', 10), ('prodct3', 12)]

5.1.12 zip()组合多个列表

list1 = [1, 2, 3, 4]
list2 = [10, 20, 30]
combine = list(zip("abcd", list1, list2))
print(combine)
# 组合后的元素式元组形式,元素个数和长度最短的那个一致
# [('a', 1, 10), ('b', 2, 20), ('c', 3, 30)]

5.1.13 扩展

1、堆栈

套娃式网站点击跳转,点击返回按钮回到上一个网站,直到回到第一个页面不能继续返回

堆栈:后进先出,python中的堆栈实现逻辑

browsing_session = []
browsing_session.append(1)
browsing_session.append(2)
browsing_session.append(3)
print(browsing_session)
while browsing_session:
    last = browsing_session.pop()
    if not browsing_session:
        print("已经回到初始页面了")
    else:
        now = browsing_session[-1]
        print(f"从{last}回到{now}")

2、队列

队列:先进先出,类似商店排队

前面的移出后  后面的需要移动一个位置,使用deque里的popleft()方法可以便捷操作

from collections import deque
queue = deque([])
queue.append(1)
queue.append(2)
queue.append(3)
print(queue)
# deque([1, 2, 3])
while queue:
    last = queue.popleft()
    print(last)
    if not queue:
        print("队列空了")

5.2 tuple 元组

 

5.2.1 元组的定义

# 标准元组定义方法
point = (1, 2)
print(type(point))
# <class 'tuple'>

# 下面这种也可以,但是最好别这么写
point = 1, 2
print(type(point))
# <class 'tuple'>

# 定义一个空元组
point = ()

# 定义一个至于一个元素的元组,注意逗号不能少
point = (1,)
# 或者
point = 1,

 使用tuple()进行数据类型转换:

point = tuple("hello")
print(point)
# ('h', 'e', 'l', 'l', 'o')

point = tuple([1, 2])
print(point)
# (1, 2)

5.2.2 元组合并

point = (1, 2) + (3, 4)
print(point)
# (1, 2, 3, 4)
point = (1, 2) * 3
print(point)
# (1, 2, 1, 2, 1, 2)

元组不允许修改内部元素。

# 获取元组内指定下标的元素
point = (1, 2, 3)
print(point[1])
# 元组的切片操作
point = tuple(range(20))
new_point = point[1:10:2]
print(new_point)
# (1, 3, 5, 7, 9)
print(point)
# (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19)

# 把元组内元素赋值给变量
point = tuple(range(10))
first, *other, last = point
print(f"first = {first} other = {other} last {last}")
# first = 0 other = [1, 2, 3, 4, 5, 6, 7, 8] last 9

 元组的一个应用场景:两值互换

# 实现2值互换
x = 10
y = 11
x, y = y, x
print(f"x = {x} y = {y}")

补充:

python中array()也可以用来定义一个列表,但是在使用这个函数时需要指定列表内的元素的数据类型,即这个列表内以后只能存储这种类型的数据,插入或者修改为其他数据类型时就会报错,所以一般情况不会使用array()来定义列表,除非有特定的需求。

array — Efficient arrays of numeric values — Python 3.11.4 documentation

from array import array

numbers = array("i", [1, 2, 3])
numbers.insert(2, "b")
# 会报错
# Traceback (most recent call last):
#   File "test.py", line 353, in <module>
#     numbers.insert(2, "b")
# TypeError: an integer is required (got type str)

5.3 集合

集合:内部元素没有重复,集合内部数据是无序的所以不能通过下标来获取元素值,支持修改

numbers = [1, 2, 3, 3, 4]
uniques = set(numbers)
print(uniques)
# {1, 2, 3, 4}

5.3.1 集合定义

my_set = set() # 定义一个空集合 

set1 = {1, 2}

5.3.2 add(value) 添加元素

set.add(value)

set1 = {1, 2, 3, 4, "hello"}
set1.add(9)
print(set1)  # {1, 2, 3, 4, 9, 'hello'}

5.3.3 删除元素

set.remove(value)    没有返回值

set.pop(value)     返回值是被删除的那个元素

set1 = {1, 2, 3, 4, "hello"}
# 使用remove 删除集合中指定元素
temp = set1.remove(2)  
print(temp)  # None
print(set1)  # {1, 3, 4, 'hello'}

# 使用pop 删除集合中随机一个元素
temp1 = set1.pop()
print(temp1)  # 1 
print(set1)   # {3, 4, 'hello'}

5.3.4 len(set) 获取集合长度

set1 = {1, 2, 3, 4, "hello"}
l = len(set1)  
print(l)  # 5

5.3.5 clear() 清空集合

set.lear()

set1 = {1, 2, 3, 4, "hello"}
set1.clear()
print(set1)  # set()

5.3.6 获取多个集合的并集

原集合内容不变,生成一个新的集合

set1 = {1, 2, 3, 4}
set2 = {1, 3, 5, 7}
set3 = set1 | set2
print(set3)  # {1, 2, 3, 4, 5, 7}
set4 = set1.union(set2)
print(set4)  # {1, 2, 3, 4, 5, 7}

print(set1)  # {1, 2, 3, 4}
print(set2)  # {1, 3, 5, 7}

5.3.7 获取多个集合的交集

first = {1, 2, 3, 4}
second = {1, 3, 5, 7}
third = first & second
print(third)
# {1, 3}

5.3.8 获取集合的差集

语法:

集合1有  但是集合2没有的元素

集合1 - 集合2

或者 集合1.difference(集合2)

set1 = {1, 2, 3}
set2 = {1, 5, 6}
set3 = set1.difference(set2)
print(set3)  # {2, 3}
set4 = set1 - set2
print(set4)   # {2, 3}
print(set1)   # {1, 2, 3}
print(set2)   # {1, 5, 6}

5.3.9 获取多个集合的对称性差异

first = {1, 2, 3, 4}
second = {1, 3, 5, 7}
third = first ^ second
print(third)
# {2, 4, 5, 7}
# 获取first有  但是second没有的元素,和second有但是first没有的元素
# 也就是交集以外的元素

5.3.10 集合内部数据的无序性

集合内部元素不支持使用索引进行数据获取

first = {1, 2, 3, 4}

print(first[0])

# 会报错  TypeError: 'set' object is not subscriptable

5.3.11 集合遍历

集合是无序的,不支持索引,所以不能用while遍历集合

可以用for遍历集合

5.4 dictionary 字典

5.4.1 定义字典

字典的key和value可以是任意数据类型(key不能是字典)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

甜甜的凉拌苦瓜

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值