Python 列表、字典、集合、生成器、迭代器 的一些使用技巧
一、列表(List)高级用法
1.列表推导式
快速生成列表的方式:
# 基础形式
squares = [x**2 for x in range(10)]# 带条件
even_squares = [x**2 for x in range(10) if x % 2 == 0]# 嵌套循环
pairs = [(x, y) for x in range(3) for y in range(3) if x != y]
2.列表切片
a = [1, 2, 3, 4, 5]
a[1:4] # [2, 3, 4]
a[::-1] # 反转 [5, 4, 3, 2, 1]
a[::2] # 步长为2 [1, 3, 5]
3.解包赋值
a, b, *rest = [1, 2, 3, 4, 5]
# a=1, b=2, rest=[3,4,5]
4.常用技巧
# 去重(保持顺序)
unique = list(dict.fromkeys([1,2,2,3,1]))# 多层嵌套列表展开
flat = [x for row in matrix for x in row]
二、字典(Dict)高级用法
1.字典推导式
squares = {x: x**2 for x in range(5)}
2.合并与更新
Python 3.9+ 支持新语法:a = {"x": 1, "y": 2}
b = {"y": 3, "z": 4}
merged = a | b # {'x': 1, 'y': 3, 'z': 4}
3.安全取值与默认值
person = {"name": "Tom"}
age = person.get("age", 18) # 默认18
4.反转键值
reversed_dict = {v: k for k, v in person.items()}
5.有序字典(Python 3.7+ 默认保持插入顺序)
for k, v in person.items():print(k, v) # 顺序与插入时一致
三、集合(Set)高级用法
1.基本集合操作
A = {1, 2, 3}
B = {3, 4, 5}
A | B # 并集 {1,2,3,4,5}
A & B # 交集 {3}
A - B # 差集 {1,2}
A ^ B # 对称差 {1,2,4,5}
2.集合推导式
unique_squares = {x**2 for x in range(10)}
3.判断子集/超集
A <= B # A 是否为 B 的子集
A >= B # A 是否为 B 的超集
4.去重 + 保留顺序
lst = [1,2,3,2,1]
# 用 set 无法保留顺序,这个技巧更优雅。
unique = list(dict.fromkeys(lst))
四、生成器(Generator)高级用法
生成器是一种 惰性迭代对象,只有取值时才计算,节省内存。
1.基础生成器
def count_up_to(n):count = 1while count <= n:yield countcount += 1
2.生成器表达式
gen = (x**2 for x in range(10))
next(gen) # 取下一个值
3.与普通列表对比
列表:一次性生成所有值,占内存
生成器:按需生成(节省内存)
4.双向通信(send)
def greeter():name = yield "What's your name?"yield f"Hello {name}!"g = greeter()
print(next(g)) # "What's your name?"
print(g.send("Alice")) # "Hello Alice!"
五、迭代器(Iterator)高级用法
1.可迭代对象与迭代器的关系
lst = [1, 2, 3]
it = iter(lst) # 转换为迭代器
next(it) # 1
2.自定义迭代器类
class Counter:def __init__(self, low, high):self.current = lowself.high = highdef __iter__(self):return selfdef __next__(self):if self.current > self.high:raise StopIterationself.current += 1return self.current - 1for num in Counter(1, 5):print(num)
3.itertools 模块(迭代器工具集)
Python 自带的强大迭代器库:
from itertools import count, cycle, islice# 无限计数
for i in islice(count(10), 5):print(i) # 10,11,12,13,14# 无限循环
for i, x in zip(range(5), cycle("AB")):print(x) # A,B,A,B,A
实战组合例子
示例:生成 100 个随机数,去重、排序、生成平方表:
import randomnums = [random.randint(1, 50) for _ in range(100)]
unique_sorted = sorted(set(nums))
result = {x: x**2 for x in unique_sorted if x % 2 == 0}
print(result)
本文章的原文地址
GitHub主页