如何用更Pythonic的方式按含元组的索引列表提取分组元素?
更Pythonic的方式实现按结构提取列表元素
给定源列表和结构混合的索引列表(元素可为单个索引或索引元组),我们可以用更简洁、通用的方式实现结构一致的元素提取,替代原有的循环写法:
方案1:列表推导式(最简洁,支持任意长度元组)
list_of_things = ["one", "two", "three", "four", "five"] list_of_indices = [(3, 1), (2, 0), 4] desired_result = [ tuple(list_of_things[i] for i in idx) if isinstance(idx, tuple) else list_of_things[idx] for idx in list_of_indices ] print(desired_result) # 输出: [('four', 'two'), ('three', 'one'), 'five']
这个写法不仅一行完成转换,还支持任意长度的索引元组(比如三元组(0,1,2)会提取成("one","two","three")),比原代码硬编码二元组的逻辑更通用,完全适配你用matplotlib.legend_handler.HandlerTuple合并多个图例项的场景。
方案2:辅助函数+map(适合复用逻辑)
如果提取逻辑需要多次复用,或者想要更清晰的代码结构,可以封装成函数后用map批量处理:
list_of_things = ["one", "two", "three", "four", "five"] list_of_indices = [(3, 1), (2, 0), 4] def get_artist_group(idx): if isinstance(idx, tuple): return tuple(list_of_things[i] for i in idx) return list_of_things[idx] desired_result = list(map(get_artist_group, list_of_indices))
后续如果需要调整索引处理逻辑(比如支持其他可迭代类型),只需修改get_artist_group函数即可,维护性更强。
方案3:生成器表达式(适合按需迭代)
如果不需要立即生成完整列表,只是要迭代处理结果,可以用生成器表达式节省内存:
result_gen = ( tuple(list_of_things[i] for i in idx) if isinstance(idx, tuple) else list_of_things[idx] for idx in list_of_indices ) # 需转成列表时执行 list(result_gen)
内容的提问来源于stack exchange,提问作者sandcountyfrank
相关产品推荐
相关产品推荐

