大数定义
title:Example
定义一个10亿整数# 法一
a = 10 * 10000 * 10000
# 法二
b = 10_0000_0000
# 法三
c = 10 ** 9
# 以上结果都是10亿变量值交换
title:Example
交换变量整数a, b = b, a
# a与b交换逻辑判断
title:Example
逻辑判断在c中
if(a >= 90 && a <= 100){;}在python中
if 90 <= a <= 100:合并列表
extend的取代方法
a = [1, 2, 3]
b = [4, 5, 6, 7, 8, 9]
print(a + b)
# output:[1, 2, 3, 4, 5, 6, 7, 8, 9]列表推导式
title:Example
列表所有数据+233a = [1, 2, 3, 4]
# 法一
b = []
for e in a:
b.append(e+233)
# 法二
b = [ e+233 for e in a]
# output:[234, 235, 236, 237]字典推导式
适合把两个序列组合成映射,或对原字典做简单转换。
names = ["Tom", "Lucy", "Jack"]
scores = [80, 95, 72]
score_map = {name: score for name, score in zip(names, scores)}
print(score_map)
# output:{'Tom': 80, 'Lucy': 95, 'Jack': 72}
passed = {name: score for name, score in score_map.items() if score >= 80}
print(passed)
# output:{'Tom': 80, 'Lucy': 95}集合推导式
适合去重后再加工。
numbers = [1, 2, 2, 3, 4, 4]
even_squares = {x * x for x in numbers if x % 2 == 0}
print(even_squares)
# output:{16, 4}生成器表达式
生成器不会一次性创建完整列表,适合大数据量的逐个处理。
total = sum(x * x for x in range(1, 101))
print(total)
# output:338350三元表达式
age = 20
status = "成年" if age >= 18 else "未成年"
print(status)
# output:成年enumerate
替代手写下标变量。
names = ["Tom", "Lucy", "Jack"]
for index, name in enumerate(names, start=1):
print(index, name)zip
用于并行遍历多个容器。
names = ["Tom", "Lucy"]
scores = [80, 95]
for name, score in zip(names, scores):
print(f"{name}: {score}")解包
普通解包
point = (3, 5)
x, y = point
print(x, y)星号解包
numbers = [1, 2, 3, 4, 5]
first, *middle, last = numbers
print(first, middle, last)
# output:1 [2, 3, 4] 5函数参数解包
def add(a, b):
return a + b
args = [10, 20]
print(add(*args))
kwargs = {"a": 10, "b": 20}
print(add(**kwargs))合并字典
base = {"host": "localhost", "port": 3306}
override = {"port": 3307, "user": "root"}
config1 = {**base, **override}
config2 = base | override
print(config1)
print(config2)| 合并字典需要 Python 3.9+。
with 上下文管理器
自动处理资源释放,常用于文件、锁、网络连接等对象。
with open("demo.txt", "w", encoding="utf-8") as file:
file.write("hello")lambda
适合非常短的小函数,复杂逻辑应改成普通 def。
students = [("Tom", 80), ("Lucy", 95), ("Jack", 72)]
students.sort(key=lambda item: item[1], reverse=True)
print(students)walrus 海象运算符
:= 可以在表达式中赋值,需要 Python 3.8+。
text = "python"
if (length := len(text)) > 5:
print(length)match case
结构化模式匹配,需要 Python 3.10+。
command = ("move", 10, 20)
match command:
case ("move", x, y):
print(f"move to {x}, {y}")
case ("quit",):
print("quit")
case _:
print("unknown command")装饰器
装饰器本质是“接收函数并返回新函数”的函数,常用于日志、计时、权限检查。
def trace(func):
def wrapper(*args, **kwargs):
print(f"call {func.__name__}")
return func(*args, **kwargs)
return wrapper
@trace
def hello(name):
return f"hello {name}"
print(hello("Tom"))装饰器内容较多,单独说明见:py装饰器。
f-string
name = "Tom"
score = 95.678
print(f"{name} score={score:.2f}")
# output:Tom score=95.68语法糖使用原则
- 能明显减少样板代码时使用。
- 一行表达式太长、嵌套太深时,不要强行使用语法糖。
- 推导式适合简单映射和过滤,复杂流程用普通循环。
lambda适合短逻辑,复杂逻辑写成具名函数。- 注意版本要求:
:=需要 Python 3.8+,dict | dict需要 Python 3.9+,match case需要 Python 3.10+。
案例
py语法糖案例
Python 语法糖案例
下面这段代码集中演示常见语法糖,可以直接复制到
.py文件中运行。指向原始笔记的链接 def trace(func): def wrapper(*args, **kwargs): print(f"call {func.__name__}") return func(*args, **kwargs) return wrapper @trace def greet(name): return f"hello {name}" def main(): billion = 10_0000_0000 print("big int:", billion == 10**9) a, b = 1, 2 a, b = b, a print("swap:", a, b) score = 95 print("chain compare:", 90 <= score <= 100) numbers = [1, 2, 3, 4] print("list comprehension:", [x + 233 for x in numbers]) print("dict comprehension:", {x: x * x for x in numbers}) print("set comprehension:", {x % 3 for x in numbers}) print("generator expression:", sum(x * x for x in numbers)) age = 20 print("ternary:", "adult" if age >= 18 else "child") first, *middle, last = [1, 2, 3, 4] print("star unpack:", first, middle, last) def add(a, b): return a + b print("args unpack:", add(*[10, 20])) print("kwargs unpack:", add(**{"a": 10, "b": 20})) base = {"host": "localhost", "port": 3306} override = {"port": 3307, "user": "root"} print("dict merge:", base | override) text = "python" if (length := len(text)) > 5: print("walrus:", length) command = ("move", 10, 20) match command: case ("move", x, y): print("match:", x, y) case _: print("match: unknown") print(greet("Tom")) if __name__ == "__main__": main()