嵌套数组最优分组实现:按颜色归类姓名列表
按颜色分组姓名的高效实现方法
给定二维数组:
main_array = [['juan','blue'],['sean','red'],['ana','blue'],['alex','green']]
每个子数组第0位为姓名、第1位为颜色,需将姓名按颜色分组。先指出你提供的循环代码存在逻辑错误:判断条件误用了arr[0]=='blue'(arr[0]是姓名),且错误添加了arr[1](颜色),正确逻辑应为判断arr[1](颜色)并添加arr[0](姓名)。
以下是几种更优的实现方式:
方法1:使用collections.defaultdict(推荐)
这是最简洁高效的方案,无需提前判断颜色是否存在,自动为新颜色创建空列表:
from collections import defaultdict color_groups = defaultdict(list) for name, color in main_array: color_groups[color].append(name) # 可选:转换为普通字典 color_groups = dict(color_groups) print(color_groups) # 输出: {'blue': ['juan', 'ana'], 'red': ['sean'], 'green': ['alex']}
优势:仅需遍历数组一次,时间复杂度O(n),代码简洁易读。
方法2:使用普通字典
若不想导入模块,可手动处理字典键的存在性:
color_groups = {} for name, color in main_array: if color not in color_groups: color_groups[color] = [] color_groups[color].append(name) print(color_groups)
优势:无需额外依赖,逻辑直观,同样为O(n)时间复杂度。
方法3:使用itertools.groupby
注意:groupby要求先按分组键(颜色)排序,否则会将不连续的同颜色项拆分:
from itertools import groupby # 先按颜色排序 sorted_array = sorted(main_array, key=lambda x: x[1]) # 分组并提取姓名 color_groups = {color: [item[0] for item in group] for color, group in groupby(sorted_array, key=lambda x: x[1])} print(color_groups)
优势:适合已有序的数组,或需同时完成排序的场景;但排序会增加O(n log n)的时间复杂度。
内容的提问来源于stack exchange,提问作者Juan Sebastian Forero Noguera
相关产品推荐
相关产品推荐

