Python 列表和字典40个进阶用法,效率翻倍
 列表和字典是 Python 里用得最多的两种数据结构,但真正用熟的人不多。下面这 40 个技巧,从切片到深层合并,挑你用得上的记就行。 --- ## **一、基础高效操作** ### **1. 链式比较** ``` # 传统写法 ifx>5andxyelsey, numbers) print(f"最大值: {max_value}") # 5 ``` --- ## **七、错误处理与边界情况** ### **20. 安全获取字典值** ``` user_data = {'name': 'Alice', 'age': 25} # 安全获取不存在的键 email = user_data.get('email', '未提供') print(f"邮箱: {email}") # 邮箱: 未提供 # 使用setdefault设置默认值 user_data.setdefault('country', '中国') print(user_data) # {'name': 'Alice', 'age': 25, 'country': '中国'} ``` --- ## **八、高级数据处理** ### **21. 使用any和all进行条件判断** ``` numbers = [1, 3, 5, 7, 9] has_even = any(x%2 == 0forxinnumbers) print(f"是否有偶数: {has_even}") # False all_positive = all(x>0forxinnumbers) print(f"是否都为正数: {all_positive}") # True ``` ### **22. 列表元素旋转** ``` defrotate_list(lst, k): """将列表元素向右旋转k个位置""" k = k%len(lst) # 处理k大于列表长度的情况 returnlst[-k:] +lst[:-k] my_list = [1, 2, 3, 4, 5] rotated = rotate_list(my_list, 2) print(f"旋转后: {rotated}") # [4, 5, 1, 2, 3] ``` ### **23. 字典键值交换(处理重复值)** ``` defswap_dict_with_duplicates(original): """处理有重复值的字典键值交换""" result = {} forkey, valueinoriginal.items(): ifvaluenotinresult: result[value] = [key] else: result[value].append(key) returnresult original = {'a': 1, 'b': 2, 'c': 1, 'd': 3} swapped = swap_dict_with_duplicates(original) print(swapped) # {1: ['a', 'c'], 2: ['b'], 3: ['d']} ``` ### **24. 列表分块处理** ``` defchunk_list(lst, chunk_size): """将列表分成指定大小的块""" return [lst[i:i+chunk_size] foriinrange(0, len(lst), chunk_size)] numbers = list(range(1, 11)) chunks = chunk_list(numbers, 3) print(f"分块结果: {chunks}") # [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]] ``` ### **25. 字典值排序并获取键** ``` defget_keys_sorted_by_value(dictionary, reverse=False): """根据值排序并返回对应的键""" return [kfork, vinsorted(dictionary.items(), key=lambdax: x[1], reverse=reverse)] scores = {'Alice': 85, 'Bob': 92, 'Charlie': 78, 'David': 95} sorted_keys = get_keys_sorted_by_value(scores, reverse=True) print(f"按分数降序排列的名字: {sorted_keys}") # ['David', 'Bob', 'Alice', 'Charlie'] ``` ### **26. 列表元素频率统计(不使用Counter)** ``` deffrequency_count(lst): """手动实现元素频率统计""" freq = {} foriteminlst: freq[item] = freq.get(item, 0) +1 returnfreq items = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple'] freq = frequency_count(items) print(f"元素频率: {freq}") # {'apple': 3, 'banana': 2, 'orange': 1} ``` ### **27. 字典深度合并** ``` defdeep_merge_dicts(dict1, dict2): """深度合并两个字典,处理嵌套字典""" result = dict1.copy() forkey, valueindict2.items(): ifkeyinresultandisinstance(result[key], dict) andisinstance(value, dict): result[key] = deep_merge_dicts(result[key], value) else: result[key] = value returnresult dict1 = {'a': 1, 'b': {'x': 10, 'y': 20}} dict2 = {'b': {'y': 30, 'z': 40}, 'c': 3} merged = deep_merge_dicts(dict1, dict2) print(merged) # {'a': 1, 'b': {'x': 10, 'y': 30, 'z': 40}, 'c': 3} ``` ### **28. 列表元素滑动窗口** ``` defsliding_window(lst, window_size): """生成滑动窗口""" foriinrange(len(lst) -window_size+1): yieldlst[i:i+window_size] numbers = [1, 2, 3, 4, 5, 6] windows = list(sliding_window(numbers, 3)) print(f"滑动窗口: {windows}") # [[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6]] ``` ### **29. 字典键值类型转换** ``` defconvert_dict_types(dictionary, key_type=str, value_type=int): """转换字典键值的类型""" return {key_type(k): value_type(v) fork, vindictionary.items()} original = {'1': '10', '2': '20', '3': '30'} converted = convert_dict_types(original, key_type=int, value_type=int) print(f"转换后: {converted}") # {1: 10, 2: 20, 3: 30} ``` ### **30. 列表元素排列组合** ``` fromitertoolsimportpermutations, combinations items = ['A', 'B', 'C'] perms = list(permutations(items, 2)) print(f"排列结果: {perms}") # [('A', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'C'), ('C', 'A'), ('C', 'B')] combs = list(combinations(items, 2)) print(f"组合结果: {combs}") # [('A', 'B'), ('A', 'C'), ('B', 'C')] ``` ### **31. 字典值提取与转换** ``` defextract_and_transform(dictionary, key_list, transform_func=None): """提取指定键的值并应用转换函数""" result = [] forkeyinkey_list: ifkeyindictionary: value = dictionary[key] iftransform_func: value = transform_func(value) result.append(value) returnresult data = {'name': 'Alice', 'age': '25', 'score': '95.5'} keys = ['name', 'age', 'score'] values = extract_and_transform(data, keys, transform_func=lambdax: x.upper() ifisinstance(x, str) elsex) print(f"提取并转换的值: {values}") # ['ALICE', '25', '95.5'] ``` ### **32. 列表元素交错合并** ``` definterleave_lists(*lists): """交错合并多个列表""" result = [] max_len = max(len(lst) forlstinlists) foriinrange(max_len): forlstinlists: ifi3) print(f"过滤结果: {filtered}") # {'apple': 5, 'orange': 8} # 过滤键包含'a'的项 filtered_by_key = filter_dict_by_condition(data, lambdak, v: 'a'ink) print(f"按键过滤结果: {filtered_by_key}") # {'apple': 5, 'banana': 3, 'grape': 2} ``` ### **34. 列表元素运行总和** ``` defrunning_sum(lst): """计算列表元素的运行总和""" total = 0 result = [] fornuminlst: total += num result.append(total) returnresult numbers = [1, 2, 3, 4, 5] sums = running_sum(numbers) print(f"运行总和: {sums}") # [1, 3, 6, 10, 15] ``` ### **35. 字典键值对批量更新** ``` defbatch_update_dict(original, updates): """批量更新字典,支持嵌套键""" result = original.copy() forkey_path, valueinupdates.items(): if'.'inkey_path: # 处理嵌套键 keys = key_path.split('.') current = result forkinkeys[:-1]: current = current.setdefault(k, {}) current[keys[-1]] = value else: result[key_path] = value returnresult user = {'name': 'Alice', 'profile': {'age': 25}} updates = {'name': 'Alice Smith', 'profile.age': 26, 'profile.city': 'Beijing'} updated = batch_update_dict(user, updates) print(updated) # {'name': 'Alice Smith', 'profile': {'age': 26, 'city': 'Beijing'}} ``` ### **36. 列表元素模式匹配** ``` deffind_pattern(lst, pattern): """在列表中查找特定模式""" pattern_len = len(pattern) matches = [] foriinrange(len(lst) -pattern_len+1): iflst[i:i+pattern_len] == pattern: matches.append(i) returnmatches sequence = [1, 2, 3, 1, 2, 3, 4, 1, 2, 3] pattern = [1, 2, 3] positions = find_pattern(sequence, pattern) print(f"模式出现位置: {positions}") # [0, 3, 7] ``` ### **37. 字典值统计摘要** ``` defdict_summary(dictionary): """生成字典值的统计摘要""" ifnotdictionary: return {} values = list(dictionary.values()) numeric_values = [vforvinvaluesifisinstance(v, (int, float))] summary = { 'count': len(dictionary), 'keys': list(dictionary.keys()), 'value_types': {type(v).__name__forvinvalues} } ifnumeric_values: summary.update({ 'min': min(numeric_values), 'max': max(numeric_values), 'sum': sum(numeric_values), 'avg': sum(numeric_values) /len(numeric_values) }) returnsummary data = {'a': 10, 'b': 20, 'c': 30, 'd': 'text'} summary = dict_summary(data) print(f"字典摘要: {summary}") ``` ### **38. 列表元素差异分析** ``` deflist_differences(list1, list2): """分析两个列表的差异""" set1, set2 = set(list1), set(list2) return { 'only_in_list1': list(set1-set2), 'only_in_list2': list(set2-set1), 'common': list(set1&set2), 'union': list(set1|set2) } list_a = [1, 2, 3, 4, 5] list_b = [4, 5, 6, 7, 8] diff = list_differences(list_a, list_b) print(f"列表差异分析: {diff}") ``` ### **39. 字典键路径访问** ``` defget_nested_value(dictionary, key_path, default=None): """通过点分隔的路径访问嵌套字典值""" keys = key_path.split('.') current = dictionary forkeyinkeys: ifisinstance(current, dict) andkeyincurrent: current = current[key] else: returndefault returncurrent data = { 'user': { 'profile': { 'name': 'Alice', 'age': 25, 'address': { 'city': 'Beijing', 'zip': '100000' } } } } name = get_nested_value(data, 'user.profile.name') city = get_nested_value(data, 'user.profile.address.city') country = get_nested_value(data, 'user.profile.address.country', 'China') print(f"姓名: {name}") # Alice print(f"城市: {city}") # Beijing print(f"国家: {country}") # China ``` ### **40. 列表元素权重随机选择** ``` importrandom defweighted_random_choice(items, weights): """根据权重随机选择列表元素""" iflen(items) != len(weights): raiseValueError("Items and weights must have the same length") total = sum(weights) r = random.uniform(0, total) cumulative = 0 foritem, weightinzip(items, weights): cumulative += weight ifr<= cumulative: returnitem returnitems[-1] # 安全返回 fruits = ['apple', 'banana', 'orange'] weights = [0.5, 0.3, 0.2] # 模拟多次选择 choices = [weighted_random_choice(fruits, weights) for_inrange(1000)] print(f"苹果出现次数: {choices.count('apple')}") print(f"香蕉出现次数: {choices.count('banana')}") print(f"橙子出现次数: {choices.count('orange')}") ``` --- 40 个技巧不用全背,前 20 个属于高频场景,基本每天都能用到。21-40 更偏工具性,遇到对应问题时翻出来用比硬记更实际。`itertools`、`collections`、`functools` 这三个标准库模块值得单独花时间读一遍文档,收益很高。 **“无他,惟手熟尔”!**有需要的用起来! **如果你觉得这篇文章有用,欢迎点赞、转发、收藏、留言、推荐**❤!