01. 列表推导式(List Comprehension)
squares=[x**2 for x in range(10)]
print(squares)
02. enumerate 的妙用
for i, value in enumerate(['a', 'b', 'c']):
print(i, value)
03. zip 同步遍历多个列表
names=['Tom','Jerry']
ages=[20, 25]
for name, age in zip(names, ages):
print(name, age)
04. 字典的 get 方法
person= {'name':'Alice', 'age':30}
print(person.get('age'))
05. lambda 匿名函数
add=lambda x, y: x+y
print(add(3, 5))
06. 装饰器(Decorator)
def decorator(func):
def wrapper():
print("Before")
func()
print("After")
return wrapper
@decorator
def say_hello():
print("Hello")
say_hello()
07. *args 和 **kwargs
def demo(*args, **kwargs):
print(args)
print(kwargs)
08. 切片(Slicing)
a=[1,2,3,4,5]
print(a[1:4]) # [2, 3, 4]
print(a[::-1]) # [5, 4, 3, 2, 1]
09. 列表/集合/字典推导式
squared={x: x**2 for x in range(5)}
unique={x for x in 'hello'}
print(squared)
print(unique)
10. Python 中的 is 与 == 区别
a = [1, 2]
b = [1, 2]
print(a==b) # True
print(a is b) # False
11. with 上下文管理器
with open('file.txt', 'r') as f:
content=f.read()
12. try/except 异常处理
try:
1/0
except ZeroDivisionError as e:
print("错误:", e)
14. 类属性与实例属性的区别
class Demo:
class_var=0
def __init__(self):
self.instance_var=1
demo = Demo()
print(demo.class_var)
print(demo.instance_var)
class MyClass:
def __init__(self, attribute):
self.attribute = attribute
def method(self):
print(f"The attribute is: {self.attribute}")
# 创建MyClass的实例
obj = MyClass("Hello, World!")
# 访问属性并调用方法
print(obj.attribute) # 输出: Hello, World!
obj.method() # 输出: The attribute is: Hello, World!
15. Pythonic 的代码风格
- 海象运算符walrus operator:可以在赋值的同时返回变量的值
data = '12345678901234'
if (n := len(data)) > 10: print(f"数据量过大:{n}")
- 函数式思维:利用map和filter组合来处理数据。
data = [1,2,3,4,5,6,7,8,9]
# 传统方式
results = []
for x in data:
if x % 2 == 0:
results.append(x*2)
print(results)
# Pythonic
results = list(map(lambda x: x*2, filter(lambda x: x%2==0, data)))
print(results)
- 部分参数冻结:使用functools.partial来预配置函数参数。
from functools import partial
# 创建预配置函数
record_log = partial(print, "[DEBUG]", flush=True)
record_log("Connection established")
# 传统方式
temp = a
a = b
b = temp
# Pythonic
a, b = b, a
# 普通写法
if 0 < x and x < 100:
# Pythonic
if 0 < x < 100:
# 旧方法
merged = {**dict1, **dict2}
# Pythonic 3.9+
merged = dict1 | dict2