feat: python

This commit is contained in:
heyong.fu
2026-05-06 11:21:42 +08:00
commit 0abf1ad3c4
62 changed files with 7598 additions and 0 deletions
+133
View File
@@ -0,0 +1,133 @@
# 基础打印
print("Hello Word")
print(100)
print(3.14)
print(True)
# 多个值
# 会自动用空格分开
name = "小明"
age = 18
print(name, age) # 小明 18
# print 参数
# 1. sep 分隔符
# sep 参数可以将多个输出对象用指定分隔符进行分割,默认情况下,print使用的是空格
print("小明", 18, sep=",") # 小明,18
print("", "", "", sep="-") # 年-月-日
print("Hello", "World", sep="") # HelloWorld 无分割
print("Python", "Java", "javascript", sep="|") # Python|Java|javascript
# 2.end 结束符
# 用于指定输出结尾的字符,默认值是换行(\n)
print("第一行")
print("第二行")
print("Hello", end=" ")
print("World", end="!") # Hello World!
print()
print("加载中", end="")
print("....", end="") # 加载中....
print()
# 组合使用sep和end
print("苹果", "香蕉", "西瓜", sep=", ", end="都是水果") # 苹果, 香蕉, 西瓜都是水果
print()
print("姓名", "年龄", "城市", sep="|", end="\n----\n")
print("张三", 25, "北京", sep="|")
# 姓名|年龄|城市
# ----
# 张三|25|北京
# 3. file 输出到文件
# file 参数用于指定输出文件目标,默认是sys.stdout(标准输出,屏幕)。可以将输出重定向到文件或者标准错误流。
with open("optput.txt", "w", encoding="utf-8") as f:
print("这是写入的文件的内容", file=f)
print("这是第二行内容", file=f)
# 输出到标准错误
import sys
print("这是一个错误信息", file=sys.stderr)
# 输出到多个目标
with open("log.txt", "w", encoding="utf-8") as fs:
msg = "重要信息"
print(msg) # 输出到屏幕
print(msg, file=fs) # 输出到log.txt
# 4 flush 强制舒心缓冲区
# flush 参数用于控制输出缓冲区的刷新行为。默认是False,输出内容先存储在缓冲区中,系统决定合适显示。设置为True时,内容会立即展示
import time
# print("开始", end="")
# time.sleep(2)
# print("结束")
# 使用flush
# print("开始", end="", flush=True)
# time.sleep(2)
# print("结束")
# print("下载中", end="", flush=True)
# for i in range(5):
# time.sleep(0.5)
# print(".", end="", flush=True)
# print("完成")
# 格式化输出
# 1. f{} 在字符串前加上f,通过{}包裹变量或者表达式
name = "Bob"
age = 20
sorce = 98.88
print(f"姓名{name},年龄{20},成绩{100}")
# 表达式计算
print(f"年龄{age+1}")
print(f"分数翻倍{sorce*2}")
# 数字格式换(会四舍五入)
print(f"分数保留1位小数{sorce:.1f}") # 98.8
print(f"分数保留2位小数{sorce:.2f}") # 98.82
# 对齐
print(f"{name:>10}") # 右对齐,宽度是10 Bob
print(f"{name:<10}") # 左对齐,宽度是10 Bob
print(f"{name:^10}") # 居中对齐
# 进制转换
num = 255
print(
f"十进制{num},十六进制{num:x},二进制{num:b}"
) # 十进制255,十六进制ff,二进制11111111
# 2. format() 方法
# format方法是python3中常用的字符串格式化的方式,兼容性比较好
name = "Bob"
age = 30
sorce = 90.52
# 按顺序填充
print("姓名{},年龄{},成绩{}".format(name, age, sorce))
# 按指定索引填充
print("姓名{2},年龄{0},成绩{1}".format(age, sorce, name))
# 使用关键字填充
print("姓名{n},年龄{a},成绩{s}".format(n=name, a=age, s=sorce))
# 数字格式化
print("保留一位小数{:.1f}".format(sorce))
# 对齐和填充
print("{:<10}{:>10}".format(name, age))
# 3. % 传统格式化
# % 格式化是Pyhon早期格式化字符串的方式,目前仍在使用,但不推荐
name = "Bob"
age = 30
sorce = 90.52
print("姓名:%s,年龄:%d,分数:%.2f" % (name, age, sorce))
# %s 字符串
# %d 整数
# %f 浮点数
# %.2f 保留两位小数
print(0b1010 + 0o12 + 0xA)
+109
View File
@@ -0,0 +1,109 @@
# 整型
# 整型int 包括正整数,负整数,和零
# 基本整型定义
positive = 42
negative = -15
zero = 0
print(f"positive{positive},类型{type(positive)}") # positive42,类型<class 'int'>
print(f"negative{negative},类型{type(negative)}") # negative-15,类型<class 'int'>
print(f"zero{zero},类型{type(zero)}") # zero0,类型<class 'int'>
# 支持不同进制的整型表示
# 十进制 (默认)
decimal = 10
print(f"十进制 10: {decimal}")
# 二进制 (以 0b 或 0B 开头)
binary = 0b1010 # 二进制 1010 = 十进制 10
print(f"二进制 0b1010: {binary}")
# 八进制 (以 0o 或 0O 开头)
octal = 0o12 # 八进制 12 = 十进制 10
print(f"八进制 0o12: {octal}")
# 十六进制 (以 0x 或 0X 开头)
hexadecimal = 0xA # 十六进制 A = 十进制 10
print(f"十六进制 0xA: {hexadecimal}")
# 使用下划线提高可读性 (Python 3.6+)
large_number = 1_000_000
print(f"大数字: {large_number}")
credit_card = 1234_5678_9012_3456
print(f"信用卡号: {credit_card}")
bytes_value = 0b1100_1010_1111_0101
print(f"字节值: {bytes_value}")
# 整型转换
# int()
print(f"int(3.14) = {int(3.14)}") # 3
print(f"int(-2.99) = {int(-2.99)}") # -2
print(f"int('100') = {int('100')}") # 100
print(f"int('1010', 2) = {int('1010', 2)}") # 二进制字符串转十进制
print(f"int('FF', 16) = {int('FF', 16)}") # 十六进制字符串转十进制
print(f"int(True)={int(True)}") # 1
print(f"int(False)={int(False)}") # 0
# 进制转换函数
number = 10
print(f"\n数字 {number} 的不同进制表示:")
print(f"二进制: {bin(number)}") # 0b1010
print(f"八进制: {oct(number)}") # 0o12
print(f"十六进制: {hex(number)}") # 0xa
# 基本运算符
a, b = 10, 3
print("基本算术运算:")
print(f"{a} + {b} = {a + b}") # 加法: 13
print(f"{a} - {b} = {a - b}") # 减法: 7
print(f"{a} * {b} = {a * b}") # 乘法: 30
print(f"{a} / {b} = {a / b}") # 除法: 3.333... (返回浮点数)
print(f"{a} // {b} = {a // b}") # 整除: 3
print(f"{a} % {b} = {a % b}") # 取余: 1
print(f"{a} ** {b} = {a ** b}") # 幂运算: 1000
print(f"-{a} = {-a}") # 取负: -10
print(f"+{a} = {+a}") # 取正: 10
a, b = 10, 5
print("比较运算:")
print(f"{a} == {b}: {a == b}") # 等于: False
print(f"{a} != {b}: {a != b}") # 不等于: True
print(f"{a} > {b}: {a > b}") # 大于: True
print(f"{a} < {b}: {a < b}") # 小于: False
print(f"{a} >= {b}: {a >= b}") # 大于等于: True
print(f"{a} <= {b}: {a <= b}") # 小于等于: False
# 链式比较
c = 7
print(f"\n链式比较:")
print(f"{b} < {c} < {a}: {b < c < a}") # True
print(f"{a} > {c} > {b}: {a > c > b}") # True
import math
numbers = [-5, 0, 5, 10, 15]
print("内置数学函数:")
for num in numbers:
print(f"abs({num}) = {abs(num)}") # 绝对值
print(f"\n最大值: {max(1, 5, 2, 8, 3)}") # 8
print(f"最小值: {min(1, 5, 2, 8, 3)}") # 1
print(f"求和: {sum([1, 2, 3, 4, 5])}") # 15
# 更多数学函数
print(f"\n高级数学函数:")
print(f"2的3次方: {pow(2, 3)}") # 8
print(f"四舍五入: {round(3.14159, 2)}") # 3.14
print(f"向上取整: {math.ceil(3.14)}") # 4
print(f"向下取整: {math.floor(3.14)}") # 3
n = 3
print(int(n**0.5))
+248
View File
@@ -0,0 +1,248 @@
# 字符串
str1 = "字符串"
print(str1, type(str1)) # 字符串 <class 'str'>
# 1.字符串转义字符
# \n 换行
# \t 制表符(Tab
# \\ 标识反斜杠自身
# \' 单引号
# \" 双引
# uXXXX 标识Unicode字符
# 如果不需要将反斜杠作为转义符使用,可以在字符前面加r,表示原始字符串,反斜杠不会被转移
str2 = "\n"
print(str2)
str3 = "制表\t"
print(str3) # 制表 符
str4 = "反斜杠\\自身"
print(str4) # 反斜杠\自身
str5 = '单引"'
print(str5) # 双引号
str6 = r"原始字符串\n不会被转义"
print(str6) # 原始字符串\n不会被转义
# 2.字符串索引和切片
# 字符串中的每个字符都可以通过索引(下标)来访问。索引从0开始,也支持负数索引(-1表示最后一个字符,-2表示倒数第二个,以此类推)。
text = "Hello Python"
print("索引操作:")
print(f"字符串: '{text}'")
print(f"字符串长度{len(text)}") # 字符串长度12
print(f"正索引-text[0]:{text[0]}") # H
print(f"正索引-text[6]:{text[6]}") # P
print(f"负索引-text[-1]:{text[-1]}") # n
print(f"负索引-text[-6]:{text[-6]}") # P
# 切片(slice)可以用来获取字符串中的一部分,语法为 `str[start:end:step]`,其中:
# - `start`:起始索引(包含该位置,默认为0)
# - `end`:结束索引(不包含该位置,默认为字符串长度)
# - `step`:步长(默认为1,可以为负数实现反向切片)
text = "Hello Python Programming"
print(f"text[0:5]:{text[0:6]}") # Hello
print(f"text[6:12]: '{text[6:12]}'") # Python
print(f"text[:5]: '{text[:5]}'") # Hello (从开始到索引5)
print(f"text[13:]: '{text[13:]}'") # Programming (从索引13到结束)
print(f"text[-11:]: '{text[-11:]}'") # Programming (从倒数第11个到结束)
# 切片步长
print(f"text[::2]:{text[::2]}") # HloPto rgamn
print(f"text[1::2]: '{text[1::2]}'") # el yhnPormig (从索引1开始,步长为2)
print(f"text[::-1]: '{text[::-1]}'") # gnimmargorP nohtyP olleH (反转)
# 字符串操作方法
# 大小写转换
# upper()全部转大写
# lower() 全部转小写
# capitalize()首字母大写,其余小写
# title()每个单词首字母大写
# swapcase()大小写互换
text = "hello World of Python"
print(f"转大写{text.upper()}") # WORLD OF PYTHON
print(f"转小写{text.lower()}") # world of python
print(f"首字母大写{text.capitalize()}") # Hello world of python
print(f"每个单词首字母大写{text.title()}") # Hello World Of Python
print(f"大小写互换{text.swapcase()}") # HELLO wORLD OF pYTHON
# 查找和替换
# find(sub) 查找子串,返回索引,找不到返回-1
# rfind(sub) 从右侧查找
# index(sub) 找到子串,找不到抛出异常
# count(sub) 统计子串出现次数
# replace(old,new,count) 替换子串
text = "Hello World, Welcome to Python World"
print(f"查找Welcome出现的位置{text.find('Welcome')}") # 13
print(f"查找不存在的{text.find('java')}") # -1
print(f"从右侧查找{text.rfind('Python')}") # 24
print(f"从索引查找{text.index('Python')}") # 24
print(f"出现次数{text.count('Python')}") # 1
print(f"替换{text.replace('Python','Java')}") # Hello World, Welcome to Java World
# 字符串检查
# isalpha():是否全为字母
# isdigit():是否全为数字
# isalnum():是否全为字母或数字
# isspace():是否全为空白字符(如空格、制表符等)
# istitle():是否为标题格式(每个单词首字母大写)
# isupper():是否全为大写字母
# islower():是否全为小写字母
# startswith(): 是否以指定子串开头
# endswith(): 是否以指定子串结尾
def string_checks():
test_cases = [
"Hello123", # 字母数字
"12345", # 纯数字
"Hello", # 纯字母
" ", # 纯空格
"HELLO", # 全大写
"hello", # 全小写
"Hello World", # 包含空格
"", # 空字符串
]
print("字符串检查")
for s in test_cases:
print(
f"{s:12}: 字母={s.isalpha():5} 数字={s.isdigit():5} 数字字母={s.isalnum():5} 空格={s.isspace():5} 标题={s.istitle():5}"
)
# string_checks()
# 开头结尾检查
filename = "document.pdf"
url = "https://www.example.com"
print(f"\n文件{filename}是PDF嘛?{filename.endswith('pdf')}")
print(f"URL'{url}' 以https开头吗? {url.startswith('https')}")
# 去除空格和填充
# 去除空白字符和字符串填充方法用于格式化字符串内容。
# strip():去除字符串两端的空白字符(包括空格、制表符、换行等)
# lstrip():去除左侧空白
# rstrip():去除右侧空白-
# strip([chars]) 也可以去除指定字符(如'*'、'0'等)-
# center(width, fillchar):内容居中,两侧用fillchar填充
# ljust(width, fillchar):内容左对齐,右侧用fillchar填充
# rjust(width, fillchar):内容右对齐,左侧用fillchar填充
# zfill(width):左侧用0填充,常用于数字字符串
text = " Hello World "
print(f"原始: |{text}|")
# 去除字符串两边空格
print(f"去除字符串两边空格|{text.strip()}|")
# 去除左边空格
print(f"去除字符串左侧空格|{text.lstrip()}|")
# 去除右边有空格
print(f"去除字符串右侧空格|{text.rstrip()}|")
# 包含特定字符的字符串
text2 = "***Hello World***"
print(f"去除指定字符|{text2.strip("*")}|")
text3 = "Hello"
# 将字符串居中填充到20个字符宽度并输出
print(f"居中: |{text3.center(20)}|")
# 将字符串左对齐填充到20个字符宽度并输出
print(f"左对齐: |{text3.ljust(20)}|")
# 将字符串右对齐填充到20个字符宽度并输出
print(f"右对齐: |{text3.rjust(20)}|")
# 使用0在左侧填充字符串到10个字符宽度
print(f"右对齐: |{text3.zfill(10)}|") # 00000Hello
# 分割和连接
# split(sep=None, maxsplit=-1):将字符串按指定分隔符分割成列表,sep为分隔符,maxsplit为分割次数,默认全部分割。
# rsplit(sep=None, maxsplit=-1):从右侧开始分割,其他用法同split。
# splitlines(keepends=False):按行分割字符串,返回每一行组成的列表,keepends为True时保留换行符。
# join(iterable):用指定字符串连接可迭代对象中的元素,生成一个新的字符串。
csv_data = "apple,banana,orange,grape"
sentence = "Hello World of Python"
lines = "第一行\n第二行\n第三行"
print(f"csv分割{csv_data.split(',')}") # ['apple', 'banana', 'orange', 'grape']
print(f"句子分割{sentence.split()}") # ['Hello', 'World', 'of', 'Python']
print(f"限制分割{sentence.split(' ',2)}") # ['Hello', 'World', 'of Python']
print(f"按行分割{lines.splitlines()}") # ['第一行', '第二行', '第三行']
# 字符串连接
fruits = ["apple", "banana", "orange"]
print(f"字符串连接{','.join(fruits)}") # apple,banana,orange
print(f"字符串连接{'|'.join(fruits)}") # apple|banana|orange
# 字符串格式化
# f-string
# 语法:在字符串前加f,花括号{}中放变量或表达式。
# 例:f"姓名: {name}, 年龄: {age}"
# 优点:简洁、支持表达式、易读。
name = "Alice"
age = 25
salary = 5000.50
print("f-string格式化:")
print(f"姓名: {name}, 年龄: {age}")
print(f"薪资: ${salary:.2f}")
print(f"明年年龄: {age + 1}")
print(f"名字大写: {name.upper()}")
# 表达式和函数调用
items = ["apple", "banana", "orange"]
print(f"物品数量: {len(items)}")
print(f"第二个物品: {items[1]}")
# 格式化对齐
number = 42
print(f"右对齐: |{number:>10}|")
print(f"左对齐: |{number:<10}|")
print(f"居中对齐: |{number:^10}|")
print(f"零填充: |{number:010}|")
# format() 方法
# 语法:字符串中用{}占位,调用format()传入对应的值。
# 例:"{} is {} years old".format(name, age)
# 支持位置参数、关键字参数、格式控制。
# format() 方法
name = "Bob"
age = 30
print("format() 方法:")
print("{} is {} years old".format(name, age))
print("{0} is {1} years old. Hello {0}!".format(name, age))
print("{name} is {age} years old".format(name=name, age=age))
# 数字格式化
pi = 3.14159
print("PI = {:.2f}".format(pi))
print("二进制: {:b}".format(10))
print("十六进制: {:x}".format(255))
# % 操作符
# 语法:字符串中用%占位符,后面用%传入元组或字典。
# 例:"%s is %d years old" % (name, age)
# 占位符有%s(字符串)、%d(整数)、%f(浮点数)等。
# % 操作符 (传统方法)
name = "Charlie"
age = 35
print("% 格式化:")
print("%s is %d years old" % (name, age))
print("PI = %.3f" % 3.14159)
# 字符串不可变
# 字符串在Python中是不可变对象(immutable),这意味着一旦创建,字符串的内容就不能被直接修改。所有对字符串的操作(如拼接、替换、大小写转换等)都会返回一个新的字符串对象,原有字符串保持不变。
# 这种不可变性带来如下特点和好处:
# 安全性:字符串作为键(key)用于字典等哈希结构时,内容不会被意外更改,保证哈希值稳定。
# 多线程安全:多个线程可以安全地共享字符串对象,无需担心内容被修改。
# 高效缓存:Python可以对相同内容的字符串进行内部缓存和重用,提升性能。
# 注意:虽然不能直接修改字符串的某个字符,但可以通过切片、拼接等方式生成新的字符串。
+267
View File
@@ -0,0 +1,267 @@
# 布尔类型的基本概念
# 布尔类型只有两个值:True 和 False,用于表示真和假。
is_sunny = True
is_raining = False
print(f"is_sunny:{is_sunny},类型:{type(is_sunny)}") # is_sunny:True,类型:<class 'bool'>
print(
f"is_raining:{is_raining},类型:{type(is_raining)}"
) # is_raining:False,类型:<class 'bool'>
# True 和1 是相等
print(f"True==1:{True==1}") # True==1:True
# False 和0 是相等
print(f"False==0:{False==0}") # False==0:True
# True和True的相加结果
print(f"True+True:{True + True}") # True+True:2
# True * 10
print(f"True*10:{True *10}") # True*10:10
# # False * 10
print(f"False*10:{False *10}") # False*10:0
# 布尔运算
# 逻辑运算符用于对布尔值进行逻辑运算,主要要三种
# and(与) 只有两个操作数都为 True 时,结果才为 True,否则为 False。
# or(或) 只要有一个操作数为 True,结果就为 True,只有两个都为 False 时,结果才为 False。
# not(非) 对单个布尔值取反,True 变为 FalseFalse 变为 True。
# 逻辑运算
a, b = True, False
print("逻辑运算:")
print(f"{a} and {b} = {a and b}") # False
print(f"{a} or {b} = {a or b}") # True
print(f"not {a} = {not a}") # False
print(f"not {b} = {not b}") # True
# 真值表
print("\n真值表:")
print("AND运算:")
print(f"True and True = {True and True}") # True
print(f"True and False = {True and False}") # False
print(f"False and True = {False and True}") # False
print(f"False and False = {False and False}") # False
print("\nOR运算:")
print(f"True or True = {True or True}") # True
print(f"True or False = {True or False}") # True
print(f"False or True = {False or True}") # True
print(f"False or False = {False or False}") # False
print("\nNOT运算:")
print(f"not True = {not True}") # False
print(f"not False = {not False}") # True
# 逻辑运算符的短路特性
# 逻辑运算符在运算时具有“短路”特性,也叫“惰性求值”。
# 对于 and 运算符,如果第一个操作数为 False,就不会再计算第二个操作数,结果直接为 False。
# 对于 or 运算符,如果第一个操作数为 True,就不会再计算第二个操作数,结果直接为 True。
def expensive_operation():
print("执行了耗时操作")
return True
# and
result1 = False and expensive_operation() # 不执行
print(result1) # False
result2 = True and expensive_operation() # 执行
print(result2) # True
# or
result3 = True or expensive_operation() # 不执行
print(result3) # True
result4 = False or expensive_operation() # 执行
print(result4) # True
# 比较运算符
# 比较运算符
x, y = 10, 5
print("比较运算:")
print(f"{x} == {y}: {x == y}") # 等于: False
print(f"{x} != {y}: {x != y}") # 不等于: True
print(f"{x} > {y}: {x > y}") # 大于: True
print(f"{x} < {y}: {x < y}") # 小于: False
print(f"{x} >= {y}: {x >= y}") # 大于等于: True
print(f"{x} <= {y}: {x <= y}") # 小于等于: False
# 字符串比较
print(f"\n字符串比较:")
print(f"'apple' == 'apple': {'apple' == 'apple'}") # True
print(f"'apple' == 'banana': {'apple' == 'banana'}") # False
print(f"'apple' < 'banana': {'apple' < 'banana'}") # True (按字典序)
# 链式比较
z = 7
print(f"\n链式比较:")
print(f"{y} < {z} < {x}: {y < z < x}") # 5 < 7 < 10: True
print(f"{x} > {z} > {y}: {x > z > y}") # 10 > 7 > 5: True
print(f"{x} == {z} == {y}: {x == z == y}") # False
# 在上下文中很多用于布尔值
# Python中的假值
falsy_values = [
False, # 布尔假
None, # 空值
0, # 整数零
0.0, # 浮点数零
0j, # 复数零
"", # 空字符串
[], # 空列表
(), # 空元组
{}, # 空字典
set(), # 空集合
]
print("假值测试:")
for value in falsy_values:
if value:
print(f"{value!r:10} -> True")
else:
print(f"{value!r:10} -> False")
# !r是转成字符串
# 真值示例
truthy_values = [
True, # 布尔真
1, # 非零数字
0.1, # 非零浮点数
"hello", # 非空字符串
[1, 2, 3], # 非空列表
(1, 2), # 非空元组
{"key": "value"}, # 非空字典
{1, 2, 3}, # 非空集合
]
print("\n真值测试:")
for value in truthy_values:
if value:
print(f"{value!r:20} -> True")
else:
print(f"{value!r:20} -> False")
# 应用
# 条件语句
age = 20
has_license = True
has_car = False
# if 语句
if age >= 18:
print("已成年")
# if-else 语句
if has_license and has_car:
print("可以开车")
else:
print("不能开车")
# if-elif-else 语句
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "D"
print(f"分数 {score} -> 等级 {grade}")
# 循环
# while 循环
count = 0
while count < 5:
print(f"while循环: count = {count}")
count += 1
# break 和 continue
print("\nbreak和continue演示:")
for i in range(10):
if i == 2:
continue # 跳过本次循环
if i == 7:
break # 终止循环
print(f"i = {i}")
# 布尔函数和操作
# bool() 函数用于将一个值转换为布尔类型(True 或 False)。在 Python 中,以下情况会被视为 False:
# 数值类型的 0(如 0, 0.0, 0j
# 空序列或空集合(如 "", [], (), {}
# None
# 自定义对象的 bool 或 len 返回 False 或 0
# 其他情况都被视为 True。
# 定义一个函数用于演示bool()函数的用法
def bool_function():
# 定义一个包含多种类型测试值的列表
test_values = [0, 1, -1, 0.0, 0.1, "", "hello", [], [1], None]
# 打印测试标题
print("bool()函数测试:")
# 遍历每个测试值
for value in test_values:
# 打印每个值及其对应的bool()结果
print(f"bool({value!r:10}) = {bool(value)}")
# 调用上面定义的函数
bool_function()
# 定义一个银行账户类,用于演示自定义对象的布尔值
class BankAccount:
# 初始化方法,设置账户余额
def __init__(self, balance):
self.balance = balance
# 定义__bool__方法,余额大于0时对象为True,否则为False
def __bool__(self):
return self.balance > 0
# 定义__str__方法,返回账户余额的字符串表示
def __str__(self):
return f"BankAccount(余额: ${self.balance})"
# 打印自定义对象布尔值的测试标题
print("\n自定义对象布尔值:")
# 创建一个余额为100的账户对象
account1 = BankAccount(100)
# 创建一个余额为0的账户对象
account2 = BankAccount(0)
# 打印第一个账户对象及其bool()结果
print(f"{account1}: bool() = {bool(account1)}")
# 打印第二个账户对象及其bool()结果
print(f"{account2}: bool() = {bool(account2)}")
# any()和all()函数
# any() 和 all() 是 Python 内置的两个常用函数,用于判断可迭代对象中的元素布尔值。
# any(iterable): 只要 iterable 中有一个元素为 True(即"真值"),就返回 True;如果所有元素都为 False,则返回 False。
# all(iterable): 只要 iterable 中有一个元素为 False(即"假值"),就返回 False;只有所有元素都为 True 时才返回 True。
# any() 任意一个为True则为True
print(
f"any([False,False,False]):{any([False,False,False])}"
) # any([False,False,False]):False
print(
f"any([False,True,False]):{any([False,True,False])}"
) # any([False,True,False]):True
print(f"any([1,0,1,0]):{any([1,0,1,0])}") # any([1,0,1,0]):True
# all() 所有是true才为true
print(f"all([True, True, True]): {all([True, True, True])}") # True
print(f"all([True, False, True]): {all([True, False, True])}") # False
print(f"all([1, 1, 0]): {all([1, 1, 0])}") # False
numbers = [2, 4, 6, 8]
print(all(n % 2 == 0 for n in numbers)) # True
print(any(n % 2 != 0 for n in numbers)) # False
+27
View File
@@ -0,0 +1,27 @@
# 什么是浮点数?
# 浮点数是用来表示实数(包含小数点的数)的数据类型。在 Python 中,浮点类型用 float 表示。
pi = 3.1415926
temperature = -10.5
salary = 5000.00
scientific = 6.02e23 # 科学计数法:6.02 × 10²³
# 类型转换
# 使用float()函数进行类型转换
float_form_init = float(40)
print(float_form_init) # 40.0
float_form_str = float("99")
print(float_form_str) # 3.14
float_form_bool = float(True)
print(float_form_bool) # 1.0
float_form_false = float(False)
print(float_form_false) # 0.0
# 除法运算会产生浮点数
result1 = 10 / 2
print(result1) # 5.0
result2 = 7 / 2
print(result2) # 3.5
+68
View File
@@ -0,0 +1,68 @@
# if 语句有三种基本形式:if if-else 和 if-elif-else。
age = 20
if age >= 18:
print("成年了")
# if 条件: else:
age = 16
if age >= 18:
print("成年了")
else:
print("未成年")
# 形式三:if-elif-else 语句
# 用于判断多种可能的情况。程序会按顺序检查每一个 elif 的条件,一旦某个条件为 True,就执行对应的代码块,然后跳出整个 if 结构。如果所有 if 和 elif 的条件都不满足,则执行 else 的代码块。
score = 90
if score >= 90:
print("优秀")
elif score >= 60:
print("及格")
else:
print("不及格")
# 关键细节
# 使用缩进来区分代码块
# 通常使用4个空格作为一个缩进级别
# 同一个代码块的语句必须相同的缩进
# 条件表达式
# if 后面的“条件”可以是很广泛的表达式,其结果会被判断为 True 或 False。
# 比较运算符: == (等于), != (不等于), > (大于), < (小于), >= (大于等于), <= (小于等于)
# 逻辑运算符: and (与), or (或), not (非)
# 成员运算符: in (在...内), not in (不在...内)
age = 25
is_student = True
# 使用 and
if age >= 18 and is_student:
print("您是成年学生。")
# 使用 or
if age < 12 or age >= 65:
print("您可以享受优惠票价。")
# 使用 not
if not is_student:
print("您不是学生。")
# 使用 in
name = "Alice"
if name in ["Alice", "Bob", "Charlie"]:
print(f"你好,{name}")
# 嵌套的 if 语句
num = 10
if num > 0:
print("数字是正数")
if num % 2 == 0:
print("偶数")
else:
print("奇数")
else:
print("数字是0或者负数")
result = "11" * 2
print(result)
+107
View File
@@ -0,0 +1,107 @@
# while
# while 循环是 Python 中的一种控制流语句,用于在满足特定条件时重复执行一段代码块。只要条件为 True,循环就会一直执行
# 语法
# while 条件表达式:
# 循环主体
# 示例
count = 1
while count < 5:
print(f"这是第{count}次循环")
count += 1
# while 循环的关键要素
# 1.条件表达式
# 在每次循环开始前检查
# 如果为 True,执行循环体
# 如果为 False,退出循环
# 2.循环体
# 需要重复执行的代码
# 必须缩进(通常是4个空格)
# 3.条件更新
# 必须在循环体内更新条件变量
# 否则会导致无限循环
# 常用场景
# 计算1~100的和
sum = 0
num = 1
while num <= 100:
sum += num
num += 1
print(sum)
# 用户输入验证
# user_input = input("请输入一个正整数")
# while True:
# if user_input.isdigit() and user_input > 0:
# print(f"您输入的数字是{user_input}")
# break
# else:
# print("输入数字无效")
fruits = ["苹果", "香蕉", "栗子"]
index = 0
while index < len(fruits):
print(fruits[index])
index += 1
# 控制循环的特殊语句
# break 立刻跳出循环
# 寻找第一个能被7整除的数
num = 1
while num < 20:
if num % 7 == 0:
print(f"第一个被7整除的数{num}")
break
num += 1
# continue 跳过当前,继续下一个
# 打印0~10之间的奇数
num = 0
while num < 10:
num += 1
if num % 2 == 0:
continue
print(num)
# else 子句
# while循环可以有一个else子句
count = 1
while count < 3:
print(f"循环第{count}")
count += 1
else:
print("循环结束,退出")
# 案例
# 猜数
# import random
# secret_num = random.randint(1, 10)
# attempts = 0
# max_attempts = 7
# while attempts < max_attempts:
# attempts += 1
# guess = int(input("请输入一个数"))
# if guess < secret_num:
# print("太小了")
# if guess > secret_num:
# print("太大了")
# if guess == secret_num:
# print("恭喜你猜对了")
# break
# else:
# print(f"游戏结束,正确答案是{secret_num}")
# 注意事项
# 避免无限循环:确保循环条件最终会变为 False正确缩进:循环体内的所有代码必须正确缩进
# 更新条件变量:在循环体内更新影响条件的变量
# 使用break谨慎:过多的break语句可能使代码难以理解
abc = "Hello"
print(f"abc{'o' in abc}")
+257
View File
@@ -0,0 +1,257 @@
# 列表是什么?
# 列表 是一个有序、可变的集合,可以存储任意数量、任意类型的元素。
# 有序:元素有固定的位置(索引),按添加的顺序排列。
# 可变:创建后,可以修改列表的内容(增、删、改)。
# 异构:一个列表中可以包含不同类型的数据(整数、字符串、甚至其他列表)
# 创建列表
# 使用[]
empty_list = []
print(empty_list)
number = [1, 2, 3, 4]
mixed = [1, True, "hello"]
print(number)
print(mixed)
# 使用list()构造函数
# 创建列表除了用方括号 [],也可以用内置的 list() 函数。
# list() 可以将其他可迭代对象(如字符串、元组、字典、集合等)转换为列表。
# 如果传入一个字符串,每个字符会成为列表中的一个元素。
# 如果传入一个元组,列表会包含元组中的元素。
# 如果不传参数,会得到一个空列表。
# 字符串
list_from_string = list("abc")
print(list_from_string) # ['a', 'b', 'c']
# 元组
list_from_tuple = list((1, 2, 3))
print(list_from_tuple) # [1, 2, 3]
# 不传
list_from_empty = list()
print(list_from_empty) # []
# 访问列表元素(索引和切片)
# 索引访问 从0开始
list_number = [1, 2, 3]
print(list_number[0]) # 1
print(list_number[-1]) # 3
# print(list_number[100]) # IndexError: list index out of range
# 切片访问
# 切片用于获取列表的一个子集,语法:list[start:stop:step]
# 注意:会创建新列表,不会修改原列表
# start:起始索引(包含)
# stop:结束索引(不包含)
# step:步长(默认为1
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8]
print(numbers[2:5]) # [2, 3, 4]
print(numbers[:5]) # [0, 1, 2, 3, 4]
print(numbers[5:]) # [ 5, 6, 7, 8]
print(numbers[::2]) # [0, 2, 4, 6, 8]
print(numbers[::-1]) # [8, 7, 6, 5, 4, 3, 2, 1, 0] 反转列表
new_numer = numbers[1:4]
print(new_numer) # [1,2,3]
# 操作
# 修改元素
fruits = ["apple", "banana", "cherry"]
fruits[0] = "pick"
print(fruits) # ["pick", "banana", "cherry"]
# 添加元素
# append(x)
# 在列表末尾添加一个元素x
# insert(index,x)
# 在指定位置 index 插入元素 x,原有及后续元素后移。
# extend(iterable)
# 将另一个可迭代对象(如列表、元组等)的元素逐个添加到列表末尾。
# 注意:
# append() 是把一个元素作为整体添加到末尾
# extend() 是把所有元素分别添加到原列表
# append
a = [1, 2]
a.append([3, 4])
print(a) # [1, 2, [3, 4]] 会把[3,4] 作为一个整体添加到列表中
b = [1, 2]
b.extend([3, 4])
print(b) # [1, 2, 3, 4] 将[3,4]分别添加到列表中
c = [1, 2]
c.insert(1, 3)
print(c) # [1, 3, 2] 往指定位置添加
# 删除
# 在操作列表时,常常需要删除其中的元素。Python 提供了多种删除列表元素的方法,主要包括:
# remove(x) 方法
# 用于删除列表中第一个值为 x 的元素(如果没有这样的元素会抛出 ValueError)。
# 只会删除找到的第一个匹配项。
# 语法:list.remove(x)
# pop([index]) 方法
# 用于删除并返回给定索引处的元素。如果没有指定索引,默认删除并返回最后一个元素。
# 如果索引越界会抛出 IndexError。
# 语法:list.pop() 或 list.pop(index)
# del 语句
# del 可以根据索引删除列表的指定元素,也可以一次性删除多个元素(切片)。
# 语法:del list[index] 或 del list[start:end]
# clear() 方法
# 清空整个列表,变成空列表 []。
# 语法:list.clear()
# - remove() 删除第一个匹配的元素
fruits = ["apple", "banana", "cherry", "banana", "date"]
fruits.remove("banana")
print(fruits) # ['apple', 'cherry', 'banana', 'date']
# - pop() - 删除指定索引的元素并返回指定索引(默认删除最后一个)
fruits.pop()
print(fruits) # ['apple', 'cherry', 'banana']
fruits.pop(2)
print(fruits) # ['apple', 'cherry']
# - del(index) 按照索引删除
del fruits[0]
print(fruits) # ['cherry']
# - clear() 清空数组
fruits.clear()
print(fruits) # []
# 其他操作
# 拼接:用加号 + 可以合并两个或多个列表,形成一个新列表,不改变原列表。
# 重复:用乘号 * 可以将列表重复多次,得到新列表。
# 成员测试:使用 in 或 not in 快速判断某个元素是否存在于列表中,结果为布尔值。
# 获取长度:len(lst) 得到列表中的元素数量。
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list3 = list1 + list2
print(list3) # [1, 2, 3, 4, 5, 6]
list4 = [7, 8]
list5 = list4 * 2
print(list5) # [7, 8, 7, 8]
# 检查元素是否存在
list6 = [9, 10, 11]
print(12 in list6) # False
# 获取列表长度
print(len(list6)) # 3
# sorce()排序
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
numbers.sort()
print(numbers) # [1, 1, 2, 3, 4, 5, 6, 9]
# reverse()反转
numbers.reverse()
print(numbers) # [9, 6, 5, 4, 3, 2, 1, 1]
# 查找索引index
print(numbers.index(9)) # 0
# count() 计数
print(numbers.count(1)) # 2
# copy() 复制
numbers_copy = numbers.copy()
# 等价于
# numbers_copy = numbers[:]
# numbers_copy = list[numbers]
# 列表遍历
# 直接遍历元素
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# 遍历索引和元素
# 使用 enumerate 可以在遍历列表时同时获得每个元素的索引和值。
for index, fruit in enumerate(fruits):
print(f"索引{index}的值是{fruit}")
# 列表推导式
# 列表推导式(List Comprehensions)是 Python 提供的一种简洁优雅的构造新列表的方法。它既可以替代传统的 for 循环,也可以在创建列表时加入条件判断,让表达更加简明
# 语法
# new_list = [表达式 for 变量 in list]
# 等同于
# new_list = []
# for 变量 in list:
# new_list.append(表达式)
# 可以添加条件的列表推导式
# new_list = [表达式 for 变量 in list if 条件]
# 示例
# 生成偶数数字的平方根
num = [1, 2, 3, 4]
new_num = [n**2 for n in num if n % 2 == 0]
print(new_num) # [4, 16]
# 列表推到常用来构建,转换,筛选列表
# 构建
squares = [n**2 for n in range(5)]
print(squares) # [0, 1, 4, 9, 16]
# 转换
fruits = ["Apple", "Banana", "cherry"]
low_list = [f.lower() for f in fruits]
print(low_list) # ['apple', 'banana', 'cherry']
# 筛选
num = [1, 2, 3, 4]
new_num = [n**2 for n in num if n % 2 == 0]
print(new_num) # [4, 16]
# 多维列表
# 2x3 矩阵(二维列表)
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# 访问元素
print(matrix[0]) # [1, 2, 3] - 第一行
print(matrix[1][2]) # 6 - 第二行第三列
# 遍历二维列表
for row in matrix:
for element in row:
print(element, end=" ")
print() # 换行
# 输出:
# 1 2 3
# 4 5 6
# 7 8 9
# 注意
# 深,浅拷贝
# 浅拷贝(shallow copy)和深拷贝(deep copy)是列表复制时的两个概念,尤其是在涉及多维列表(嵌套列表)时需要特别注意。
# 浅拷贝:只复制最外层的列表对象,内部的子对象依然引用原来的地址。常用 list.copy()、切片[:] 或 list() 实现。
# 深拷贝:不仅复制最外层列表,也递归复制所有子对象,互不影响。需要用 copy.deepcopy()(需 import copy)。
# 浅拷贝
a = [[1, 2], [3, 4]]
b = a.copy()
b[1].append(5)
print(a) # [1, 2], [3, 4, 5]]
print(b) # [1, 2], [3, 4, 5]]
# 深拷贝
import copy
c = [[1, 2], [3, 4]]
d = copy.deepcopy(c)
d[1].append(5)
print(c) # [[1, 2], [3, 4]]
print(d) # [[1, 2], [3, 4, 5]]
+102
View File
@@ -0,0 +1,102 @@
# 元组 是一个有序、不可变的集合,可以存储任意数量、任意类型的元素。
# 有序:元素有固定的位置(索引),按添加的顺序排列。
# 不可变:创建后,不能修改元组的内容(不能增、删、改元素)。
# 异构:一个元组中可以包含不同类型的数据。
# 核心特性:不可变性是元组与列表最根本的区别!
# 创建方式
# 使用()
empty_tuple = ()
print(empty_tuple)
numers = (1, 2, 3, 4, 5)
fruits = ("apple", "banana", "orange")
mixed = (
"Hello",
1,
[
1,
2,
],
True,
)
print(numers)
print(fruits)
print(mixed)
# 使用tuple构造函数
# tuple() 是 Python 的一个内置函数,可以把可迭代对象(如列表、字符串、字典、集合等)转化为元组。这种方式更适合在已知有可迭代数据时创建元组,例如将列表转换为元组,或将字符串的每个字符作为元组的一个元素。
# 如果不传参数,tuple() 会返回一个空的元组。
list_data = [1, 2, 3]
tuple_from_list = tuple(list_data)
print(tuple_from_list) # (1, 2, 3)
tuple_from_string = tuple("abc")
print(tuple_from_string) # ('a', 'b', 'c')
# 创建空元组
another_enmpy_tuple = tuple()
print(another_enmpy_tuple)
# 特殊情况,单个元素的元组
# 创建单个元素的元组,需要在元组后面加,否则python会认为他是括号表达式
a_tuple = (1,)
print(a_tuple)
# 访问元组
# 通过索引
fruits = ("apple", "banana", "orange", "grape")
print(fruits[0]) # "apple" - 第一个元素
print(fruits[1]) # "banana" - 第二个元素
print(fruits[-1]) # "grape" - 最后一个元素
print(fruits[-2]) # "orange" - 倒数第二个元素
# 通过切片
numbers = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
print(numbers[2:5]) # (2, 3, 4) # 索引2到5(不含5)
print(numbers[:4]) # (0, 1, 2, 3) # 从开始到索引4
print(numbers[5:]) # (5, 6, 7, 8, 9) # 从索引5到结束
print(numbers[::2]) # (0, 2, 4, 6, 8) # 每隔一个取一个元素
print(numbers[::-1]) # (9, 8, 7, 6, 5, 4, 3, 2, 1, 0) # 反转元组
# 元组的不可变
fruits = ("apple", "banana", "cherry")
# fruits[0] = "abc" # TypeError: 'tuple' object does not support item assignment
# 如何修改元组
# 由于元组不可变,不能直接修改,但可以创建新的元组
# 直接重新赋值
fruits = ("apple", "banana", "cherry")
fruits = ("apple", "pear", "banana", "cherry") # 重新创建新元组
print(fruits) # ('apple', 'pear', 'banana', 'cherry')
# 通过拼接
fruits = ("apple", "banana", "cherry")
new_fruits = fruits[:1] + ("pear",) + fruits[1:]
print(new_fruits)
# 元组的操作与方法
# 列表操作类似,元组也支持以下常用操作(但所有操作不会改变原元组,而是产生新元组或返回新结果):
# 连接(拼接):用加号 + 组合两个元组,得到新元组。
# 重复:用乘号 * 重复元组若干次,得到新元组。
# 成员测试:用 in 或 not in 判断元素是否存在于元组中,返回布尔值。
# 获取长度:len(tuple) 返回元组包含的元素数量。
# 拼接
tuple1 = (1, 2)
tuple2 = (3, 4)
tuple3 = tuple1 + tuple2
print(tuple3) # (1, 2,3,4)
# 重复
tuple4 = tuple3 * 2
print(tuple4) # (1, 2, 3, 4, 1, 2, 3, 4)
# 是否存在
fruits = ("apple", "banana")
print("apple" in fruits) # True
# 获取长度
print(len(fruits)) # 2
+88
View File
@@ -0,0 +1,88 @@
class SimpleVM:
# 初始化方法
def __init__(self):
self.stack = []
self.locals = {}
self.globls = {}
def load_const(self, const):
# 将常量推到栈中
self.stack.append(const)
print(f"加载常量: {const} -> 栈: {self.stack}")
def store_name(self, name):
if not self.stack:
raise RuntimeError("栈为空")
# 取出值
value = self.stack.pop()
# 存储到字典中
self.locals[name] = value
print(f"存储变量: {name} = {value}")
def load_name(self, name):
if name in self.locals:
value = self.locals[name]
elif name in self.globls:
value = self.globls[name]
else:
raise RecursionError(f"name:{name} is not defined")
self.stack.append(value)
print(f"加载变量: {name} = {value} -> 栈: {self.stack}")
def binary_add(self):
if len(self.stack) < 2:
raise RecursionError("栈中元素不足")
#
a = self.stack.pop()
b = self.stack.pop()
result = a + b
self.stack.append(result)
print(f"加法: {a} + {b} = {result} -> 栈: {self.stack}")
def return_value(self):
if not self.stack:
return None
value = self.stack.pop()
print(f"返回: {value}")
return value
def vm_execution():
vm = SimpleVM()
# 输出即将执行的代码说明
print("执行代码: a = 10; b = 20; c = a + b")
# 构造指令序列
instructions = [
("LOAD_CONST", 10), # 加载常量10
("STORE_NAME", "a"), # 存储到变量a
("LOAD_CONST", 20), # 加载常量20
("STORE_NAME", "b"), # 存储到变量b
("LOAD_NAME", "a"), # 加载变量a
("LOAD_NAME", "b"), # 加载变量b
("BINARY_ADD",), # 执行加法
("STORE_NAME", "c"), # 存储到变量c
("LOAD_NAME", "c"), # 加载变量c
("RETURN_VALUE",), # 返回值
]
for instruction in instructions:
# 获取操作嘛
op = instruction[0]
# 获取操作参数
args = instruction[1:] if len(instruction) > 1 else []
# 判断不同指令,来调用不同的方法
if op == "LOAD_CONST":
vm.load_const(args[0])
elif op == "STORE_NAME":
vm.store_name(args[0])
elif op == "LOAD_NAME":
vm.load_name(args[0])
elif op == "BINARY_ADD":
vm.binary_add()
elif op == "RETURN_VALUE":
result = vm.return_value()
print(f"最终打印结果c={result}")
vm_execution()
+291
View File
@@ -0,0 +1,291 @@
def process_student_data(student_info):
"""
处理学生数据,进行类型转换和验证
参数:
student_info: 字典,包含学生信息
格式: {"name": "张三", "age": "20", "score": "85.5", "is_passed": "true"}
返回:
处理后的字典,所有值都转换为正确的Python数据类型
如果数据无效,返回None
要求:
- name: 转换为字符串,去除首尾空格
- age: 转换为整数,范围1-100
- score: 转换为浮点数,范围0.0-100.0
- is_passed: 转换为布尔值("true"/"false"字符串转为True/False
- 如果任何转换失败或超出范围,返回None
"""
try:
required_fields = ["name", "age", "score", "is_passed"]
# 校验是否字典中都存在字段
for field in required_fields:
if field not in student_info:
return None
# 将姓名取出收尾空格
name = str(student_info["name"]).strip()
if not name:
return None
# 将年龄转为整数,并检查范围
try:
age = int(student_info["age"])
if not (1 <= age <= 100):
return None
except (ValueError, TypeError):
return None
# 分数转为浮点型
try:
score = float(student_info["score"])
if not (0.0 < score < 100.0):
return None
except (ValueError, TypeError):
return None
# 处理is_passed
is_passed = str(student_info["is_passed"]).lower()
if is_passed == "true":
is_passed = True
elif is_passed == "false":
is_passed = False
else:
is_passed = None
return {"name": name, "age": age, "score": score, "is_passed": is_passed}
except Exception:
return None
def calculate_and_format_grades(students):
"""
计算学生成绩等级并格式化输出
参数:
students: 学生信息列表,每个元素是字典
格式: [{"name": "张三", "score": 85.5}, ...]
返回:
格式化后的成绩报告字符串
要求:
- 根据分数计算等级:>=90为A>=80为B>=70为C>=60为D<60为F
- 计算平均分、最高分、最低分
- 统计各等级人数
- 使用f-string格式化输出,保留2位小数
- 输出格式要美观,包含表格样式
"""
if not students:
return "没有学生数据"
def get_grade(score):
if score >= 90:
return "A"
elif score >= 80:
return "B"
elif score >= 70:
return "C"
elif score >= 60:
return "D"
else:
return "F"
student_with_grade = []
# 学生添加等级
for student in students:
score = student["score"]
grade = get_grade(score)
# 字段用**来进行解包
student_with_grade.append({**student, "grade": grade})
# 计算平均分
# 列表式推导
scores = [s["score"] for s in student_with_grade]
# 计算平均分
average_score = sum(scores) / len(scores)
# 最高分
max_score = max(scores)
# 最低分
min_score = min(scores)
# 统计每个等级的人数
grade_counts = {}
for student in student_with_grade:
grade = student["grade"]
grade_counts[grade] = grade_counts.get(grade, 0) + 1
# 输出结果
result = "成绩报告\n"
# 分割线
result += "=" * 42 + "\n"
# 添加表头
result += f"{'学生姓名':<10}{'分数':<8}{'等级':<4}\n"
result += "=" * 42 + "\n"
# 格式化输出每个学生的成绩
for student in student_with_grade:
result += (
f"{student['name']:<10}{student['score']:<8.2f}{student['grade']:<4}\n"
)
# 分割线
result += "=" * 42 + "\n"
# 平均分
result += f"平均分:{average_score}\n"
# 最高分
result += f"最高分{max_score}\n"
# 最低分
result += f"最低分{min_score}\n"
# 等级分布
grade_dist = ",".join(
[f"{grade}:{count}" for grade, count in grade_counts.items()]
)
result += f"等级分布{grade_dist}\n"
return result
def analyze_student_performance(students, filters=None):
"""
分析学生表现数据
参数:
students: 学生信息列表
filters: 筛选条件字典,可选参数
格式: {"min_score": 80, "max_score": 95, "grade": "A"}
返回:
分析结果字典,包含:
{
"total_count": 总人数,
"filtered_count": 筛选后人数,
"average_score": 平均分,
"grade_distribution": 等级分布,
"top_performers": 前3名学生,
"pass_rate": 及格率
}
要求:
- 支持按分数范围筛选
- 支持按等级筛选
- 计算及格率(>=60分)
- 找出前3名高分学生
- 处理边界情况(空数据、无效筛选条件等)
"""
# 如果没有筛选数据,返回默认值
if not filters:
return {
"total_count": 0,
"filtered_count": 0,
"average_score": 0.0,
"grade_distribution": {},
"top_performers": [],
"pass_rate": 0.0,
}
# 学生总人数
total_count = len(students)
# 拷贝一份数据
filter_students = students.copy()
# 获取当前学生等级
def get_grade(score):
if score >= 90:
return "A"
elif score >= 80:
return "B"
elif score >= 70:
return "C"
elif score >= 60:
return "D"
else:
return "F"
# 过滤大于最小分数的学生的学生数据
if "min_score" in filters:
filter_students = [
s for s in filter_students if s["score"] >= filters["min_score"]
]
# 过滤小于最大分数分的学生数据
if "max_score" in filters:
filter_students = [
s for s in filter_students if s["score"] <= filters["max_score"]
]
# 等级筛选
if "grade" in filters:
filter_grade = filters["grade"]
filter_students = [
s for s in filter_students if get_grade(s["score"]) == filter_grade
]
# 筛选后的学生数量
filter_count = len(filter_students)
# 计算平均分
if filter_students:
average_score = sum(s["score"] for s in filter_students) / filter_count
else:
average_score = 0.0
# 统计筛选后的各个等级的人数
grade_distribution = {}
for student in filter_students:
grade = get_grade(student["score"])
grade_distribution[grade] = grade_distribution.get(grade, 0) + 1
# 针对学生的分数进行排序
sorted_students = sorted(filter_students, key=lambda x: x["score"], reverse=True)
# 取前三名
top_performers = sorted_students[:3]
# 筛选出及格人数
pass_count = sum(1 for s in filter_students if s["score"] >= 60)
# 计算出及格率
pass_rate = pass_count / len(filter_students) * 100 if pass_count > 0 else 0.0
return {
"total_count": total_count,
"filter_count": filter_count,
"average_score": average_score,
"grade_distribution": grade_distribution,
"top_performers": top_performers,
"pass_rate": pass_rate,
}
# 测试数据
test_students = [
{"name": " 张三 ", "age": "20", "score": "85.5", "is_passed": "true"},
{"name": "李四", "age": "19", "score": "92.0", "is_passed": "true"},
{"name": "王五", "age": "21", "score": "78.3", "is_passed": "false"},
{"name": "赵六", "age": "22", "score": "65.7", "is_passed": "true"},
{"name": "钱七", "age": "20", "score": "45.2", "is_passed": "false"},
]
# 筛选条件测试
test_filters = [{"min_score": 80, "max_score": 95}, {"grade": "A"}, {"min_score": 60}]
# 格式化学生数据
process_students = []
for i, student in enumerate(test_students):
processed = process_student_data(student)
if processed:
process_students.append(processed)
print(f"学生{i}:{processed}")
else:
print(f"{i+1}个学生数据无效")
# 计算学生成绩与格式化
if process_students:
grade_report = calculate_and_format_grades(process_students)
print(grade_report)
# 测试数据筛选和统计分析
print("3. 数据筛选与统计:")
# 准备三组不同的筛选条件
test_filters = [{"min_score": 80}, {"grade": "A"}, {"min_score": 60, "max_score": 90}]
# 遍历筛选条件,输出分析结果
for i, filter_condition in enumerate(test_filters, 1):
print(f"筛选条件{i}:{filter_condition}")
result = analyze_student_performance(process_students, filter_condition)
print(f"总人数{result['total_count']},筛选后的人数{result['filter_count']}")
print(f"平均分{result['average_score']:.2f},及格率:{result['pass_rate']}")
print(f"等级分布{result['grade_distribution']}")
print(f"前三名{[s['name'] for s in result['top_performers']]}")
+23
View File
@@ -0,0 +1,23 @@
data_tuple = (1, 2, 3, 4, 5)
a, *b, c = data_tuple
print(a)
print(b) # [2, 3, 4]
print(c)
# 收集到一个列表并赋给 b
a, *b, c = 1, 2, 3, 4, 5
print(a)
print(b) # [2, 3, 4]
print(c)
# 字典解包
# 需要**
dict1 = {"a": 1, "b": 2}
dict2 = {"c": 3, "d": 4}
merged_dict = {**dict1, **dict2}
print(merged_dict) # {'a': 1, 'b': 2, 'c': 3, 'd': 4}
text = "Hello World"
position = text.find("r")
print(position)
+36
View File
@@ -0,0 +1,36 @@
obj_x = [10, 20]
obj_y = [10, 20]
print(obj_x == obj_y) # True 比较内容
print(obj_x is obj_y) # False 比较内存地址
# 定义一个列表,并让另一个变量引用它
obj_p = [30, 40]
obj_q = obj_p # obj_q 引用了 obj_p 所指向的同一个对象
print(obj_p == obj_q) # True 比较内容
print(obj_p is obj_q) # True 比较内存地址
# is not None 判断一个变量是否为None
my_variable = None
if my_variable is not None:
# 如果 my_variable 不是 None,则打印此消息
print("Variable is not None")
else:
# 如果 my_variable 是 None,则打印此消息
print("Variable is None")
# 错误示范:使用 != None 进行比较
# if my_variable != None:
# 如果 my_variable 不等于 None,则打印此消息
# print("Variable is not None (using != None)")
sum = 0
for i in range(5):
if i == 2:
continue
sum += i
print(sum)
+148
View File
@@ -0,0 +1,148 @@
# namedtuple是Python标准库collections模块中的一个工厂函数,用于创建具名元组。它允许你像访问对象的属性一样访问元组元素,主要作用是提高代码的可读性和可维护性。
# 2.1 主要特点:
# 具名访问:可以通过属性名访问元组元素
# 索引访问:仍然支持传统的索引访问方式
# 不可变性:与普通元组一样,创建后不可修改
# 内存效率:比普通类更节省内存
# 自描述性:通过字段名提供更好的代码可读性
"""
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
p1 = Point(10, 20)
# 通过.的方式访问
print(p1.x) # 10
# 像普通元组一样通过索引访问元素
print(p1[0]) # 10
# 多种创建方式
from collections import namedtuple
# 方式1:使用列表定义字段
Person1 = namedtuple("Person", ["name", "age", "city"])
# 创建Person具名元组类
person1 = Person1("Alice", 25, "New York")
# 创建Person实例
print(f"方式1 - 列表定义: {person1}")
# 打印方式1的结果
# 方式2:使用字符串定义字段(空格分隔)
Person2 = namedtuple("Person", "name age city")
# 创建Person具名元组类
person2 = Person2("Bob", 30, "London")
# 创建Person实例
print(f"方式2 - 字符串定义: {person2}")
# 打印方式2的结果
# 方式3:使用字符串定义字段(逗号分隔)
Person3 = namedtuple("Person", "name, age, city")
# 创建Person具名元组类
person3 = Person3("Charlie", 35, "Tokyo")
# 创建Person实例
print(f"方式3 - 逗号分隔: {person3}")
# 打印方式3的结果
# 方式4:使用元组定义字段
Person4 = namedtuple("Person", ("name", "age", "city"))
# 创建Person具名元组类
person4 = Person4("David", 28, "Paris")
# 创建Person实例
print(f"方式4 - 元组定义: {person4}")
# 打印方式4的结果
# 打印功能验证标题
for i, person in enumerate([person1, person2, person3, person4], 1):
# 遍历所有person对象
print(f"方式{i} - 姓名: {person.name}, 年龄: {person.age}, 城市: {person.city}")
# 打印每个person的属性
"""
# namedtuple的高级功能
# 获取字段信息
# 类型转换(如转为字典)
# 字段值替换,创建并返回一个新的对象
# 从字典创建实例
# 解包
# 迭代以
# 类型检查等
# 导入namedtuple,可以创建带字段名的元组类型
from collections import namedtuple
# 定义一个Person具名元组类,包含4个字段:name, age, city, job
Person = namedtuple("Person", ["name", "age", "city", "job"])
# 功能1:获取字段信息
print("1. 字段信息:")
# 打印Person类型的所有字段名
print(f" 字段名: {Person._fields}")
# 打印字段数量(长度)
print(f" 字段数量: {len(Person._fields)}")
# 功能2:转换为字典
print("\n2. 转换为字典:")
# 创建一个Person实例,包含姓名、年龄、城市和职业
person = Person("Alice", 25, "New York", "Engineer")
# 将Person实例转换为字典
person_dict = person._asdict()
# 打印原始Person对象
print(f" 原始对象: {person}")
# 打印转换后的字典
print(f" 转换后字典: {person_dict}")
# 功能3:替换字段值
print("\n3. 替换字段值:")
print(f" 原始对象: {person}")
# 使用_replace方法,替换age和city字段,生成新的Person对象
new_person = person._replace(age=26, city="Boston")
# 打印替换字段后的新对象
print(f" 替换后对象: {new_person}")
# 功能4:从字典创建
print("\n4. 从字典创建:")
# 定义一个字典,包含Person的所有字段信息
person_data = {"name": "Bob", "age": 30, "city": "London", "job": "Designer"}
# 使用**运算符,把字典内容作为参数传递,创建Person对象
person_from_dict = Person(**person_data)
# 打印从字典创建的Person对象
print(f" 从字典创建: {person_from_dict}")
# 功能5:解包操作
print("\n5. 解包操作:")
# 对person对象进行解包,分别赋值给name, age, city, job变量
name, age, city, job = person
# 打印解包后的结果
print(f" 解包结果: name={name}, age={age}, city={city}, job={job}")
# 功能6:迭代操作
print("\n6. 迭代操作:")
print(" 迭代结果:", end=" ")
for field in person:
print(field, end=" ")
# 打印换行
print()
# 功能7:类型检查
print("\n7. 类型检查:")
# 打印person对象的实际类型
print(f" 对象类型: {type(person)}")
# 检查person是否属于内置tuple类型
print(f" 是否为元组: {isinstance(person, tuple)}")
# 检查person是否属于Person类型
print(f" 是否为Person类型: {isinstance(person, Person)}")
# join
# 生成器表达式
numbers = [1, 2, 3, 4, 5]
# 将数字转换为字符串后连接
numbers_joined = ", ".join(str(num) for num in numbers)
print("数字列表连接:", numbers_joined)
words = ["hello", "world", "python"]
# 将单词转换为大写后连接
upper_joined = " ".join(word.upper() for word in words)
print("大写单词连接:", upper_joined)
+1
View File
@@ -0,0 +1 @@
重要信息
+2
View File
@@ -0,0 +1,2 @@
这是写入的文件的内容
这是第二行内容