#每天一个编程技巧# 1. 列表(List)高级技巧1.1 列表推导式与条件筛选# 基本列表推导式squares = [x**2 for x in range(10)]# 带条件的列表推导式even_squares = [x**2 for x in range(10) if x % 2 == 0]# 多重循环matrix = [[1, 2], [3, 4], [5, 6]]flattened = [num for row in matrix for num in row] # [1, 2, 3, 4, 5, 6]
1.2 列表切片技巧lst = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]# 获取最后三个元素last_three = lst[-3:] # [7, 8, 9]# 反转列表reversed_lst = lst[::-1] # [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]# 每隔两个元素取一个every_second = lst[::2] # [0, 2, 4, 6, 8]
1.3 列表排序高级用法# 基本排序lst = [5, 2, 9, 1]lst.sort() # 原地排序sorted_lst = sorted(lst) # 返回新列表# 自定义排序students = [{'name': 'Alice', 'grade': 89}, {'name': 'Bob', 'grade': 72}, {'name': 'Charlie', 'grade': 93}]# 按grade降序排序students_sorted = sorted(students, key=lambda x: x['grade'], reverse=True)# 多重排序条件from operator import itemgetterstudents.sort(key=itemgetter('grade', 'name')) # 先按grade,再按name排序
2. 字典(Dict)高级技巧2.1 字典推导式# 基本字典推导式square_dict = {x: x**2 for x in range(5)} # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}# 带条件的字典推导式even_square_dict = {x: x**2 for x in range(10) if x % 2 == 0}# 键值交换original = {'a': 1, 'b': 2, 'c': 3}inverted = {v: k for k, v in original.items()}
2.2 字典合并# Python 3.5+ 使用 ** 操作符dict1 = {'a': 1, 'b': 2}dict2 = {'b': 3, 'c': 4}merged = {**dict1, **dict2} # {'a': 1, 'b': 3, 'c': 4}# 使用 | 操作符 (Python 3.9+)merged = dict1 | dict2# 保留原始字典from collections import ChainMapchained = ChainMap(dict1, dict2)print(chained['b']) # 输出 2 (dict1中的值)
2.3 默认值处理# 使用setdefaultd = {}for k, v in [('a', 1), ('b', 2), ('a', 3)]: d.setdefault(k, []).append(v) # {'a': [1, 3], 'b': [2]}# 使用defaultdictfrom collections import defaultdictdd = defaultdict(list)for k, v in [('a', 1), ('b', 2), ('a', 3)]: dd[k].append(v) # defaultdict(<class 'list'>, {'a': [1, 3], 'b': [2]})# 使用get方法处理缺失键value = d.get('nonexistent', 'default')
3. 集合(Set)高级技巧3.1 集合运算a = {1, 2, 3, 4}b = {3, 4, 5, 6}# 并集union = a | b # {1, 2, 3, 4, 5, 6}# 交集intersection = a & b # {3, 4}# 差集difference = a - b # {1, 2}# 对称差集 (只在其中一个集合中)symmetric_diff = a ^ b # {1, 2, 5, 6}
3.2 集合推导式# 基本集合推导式squares = {x**2 for x in range(-5, 6)} # {0, 1, 4, 9, 16, 25}# 带条件的集合推导式odd_squares = {x**2 for x in range(10) if x % 2 != 0} # {1, 9, 25, 49, 81}
3.3 集合去重应用# 列表去重lst = [1, 2, 2, 3, 4, 4, 5]unique_lst = list(set(lst)) # 顺序可能改变# 保持顺序的去重from collections import OrderedDictunique_ordered = list(OrderedDict.fromkeys(lst)) # [1, 2, 3, 4, 5]
4. 元组(Tuple)高级技巧4.1 命名元组from collections import namedtuple# 创建命名元组类型Point = namedtuple('Point', ['x', 'y'])# 实例化p = Point(11, y=22)# 访问print(p.x) # 11print(p[0]) # 11 (仍然支持索引)
4.2 元组拆包# 基本拆包x, y = (1, 2)# 扩展拆包first, *middle, last = (1, 2, 3, 4, 5) # first=1, middle=[2,3,4], last=5# 忽略某些值_, second, _ = (1, 2, 3) # second=2# 字典拆包到函数参数def greet(name, age): print(f'Hello {name}, you are {age}')person = {'name': 'Alice', 'age': 25}greet(**person)
5. 高级数据结构5.1 堆(Heap)操作import heapq# 创建堆heap = []heapq.heappush(heap, 5)heapq.heappush(heap, 2)heapq.heappush(heap, 1)# 获取最小元素smallest = heapq.heappop(heap) # 1# 堆化现有列表lst = [5, 3, 1, 4, 2]heapq.heapify(lst) # 原地转换为堆# 获取n个最大/最小元素largest = heapq.nlargest(3, lst) # [5, 4, 3]smallest = heapq.nsmallest(2, lst) # [1, 2]
5.2 双端队列(deque)from collections import dequed = deque(maxlen=3) # 固定长度队列d.append(1) # [1]d.append(2) # [1, 2]d.append(3) # [1, 2, 3]d.append(4) # [2, 3, 4] (自动移除最左边的1)# 两端操作d.appendleft(0) # [0, 2, 3]d.pop() # 移除并返回3d.popleft() # 移除并返回0
5.3 计数器(Counter)
from collections import Counter# 基本计数words = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']word_counts = Counter(words) # {'apple': 3, 'banana': 2, 'orange': 1}# 获取最常见元素top_two = word_counts.most_common(2) # [('apple', 3), ('banana', 2)]# 数学运算more_words = ['apple', 'orange', 'grape']more_counts = Counter(more_words)combined = word_counts + more_counts # {'apple':4, 'banana':2, 'orange':2, 'grape':1}difference = word_counts - more_counts # {'apple':2, 'banana':2}
6. 数据结构的性能优化6.1 选择合适的数据结构操作 | 列表 | 集合 | 字典 | 查找元素 | O(n) | O(1) | O(1) | 插入 | O(1)/O(n) | O(1) | O(1) | 删除 | O(n) | O(1) | O(1) | 排序 | O(n log n) | 无 | 无 |
6.2 使用bisect维护有序列表import bisectlst = [1, 3, 4, 4, 6, 8]# 插入元素保持有序bisect.insort(lst, 5) # [1, 3, 4, 4, 5, 6, 8]# 查找插入位置index = bisect.bisect_left(lst, 4) # 2 (第一个4的位置)index = bisect.bisect_right(lst, 4) # 4 (最后一个4之后的位置)
6.3 使用数组(array)优化数值存储import array# 创建整型数组arr = array.array('i', [1, 2, 3, 4, 5]) # 比列表更节省内存# 操作类似列表arr.append(6)print(arr[2]) # 3
7. 实用技巧集合7.1 字典键的多重查找def get_value(d, *keys): for key in keys: if key in d: return d[key] return Nonedata = {'name': 'Alice', 'username': 'alice123'}name = get_value(data, 'name', 'username', 'nickname') # 'Alice'
7.2 扁平化嵌套数据结构from collections.abc import Iterabledef flatten(items): for item in items: if isinstance(item, Iterable) and not isinstance(item, (str, bytes)): yield from flatten(item) else: yield itemnested = [1, [2, [3, 4], 5]]list(flatten(nested)) # [1, 2, 3, 4, 5]
7.3 数据结构的深拷贝import copyoriginal = [[1, 2], [3, 4]]shallow = copy.copy(original) # 浅拷贝deep = copy.deepcopy(original) # 深拷贝original[0][0] = 99print(shallow) # [[99, 2], [3, 4]] (受影响)print(deep) # [[1, 2], [3, 4]] (不受影响)
掌握这些数据结构技巧将显著提升您的Python编程能力,使您能够编写出更高效、更易维护的代码。记住,选择合适的数据结构往往比算法优化更能提升程序性能。
|