如何用动态长度索引列表实现Python嵌套列表赋值?
使用动态索引列表给嵌套列表赋值的Python实现方案
在Python中,我们可以通过链式索引直接访问嵌套列表的元素,示例如下:
data = [[12, 15], [21, 22], [118, 546], [200, 1200]] assert data[0][0] == 12
现在需要实现一个通用功能:使用运行时长度动态变化的索引列表对嵌套列表进行元素赋值。比如上述示例中,对应data[0][0]的索引列表就是[0,0]。期望实现的函数签名为:
def nested_list_assignment(nested_list, list_of_indices, value):
该函数需要通过以下基础测试用例:
# 基础测试用例验证 data = [[12, 15], [21, 22], [118, 546], [200, 1200]] assert data[0][0] == 12 nested_list_assignment(data, [0, 0], 0) assert data[0][0] == 0
目前已经实现了递归版本的函数:
def nested_list_assignment(nested_list, list_of_indices, value): # 后续再处理空索引列表的情况 assert len(list_of_indices) > 0 if len(list_of_indices) == 1: nested_list[list_of_indices[0]] = value else: nested_list_assignment(nested_list[list_of_indices[0]], list_of_indices[1:], value)
Python是否提供原生语法或标准库函数实现该功能?
Python没有专门的原生语法或标准库函数直接完成这个操作,但可以通过几种简洁的方式实现,无需手写递归:
循环遍历索引(非递归实现)
通过循环逐层定位到目标元素的父容器,最后完成赋值,逻辑直观且避免递归深度限制:def nested_list_assignment(nested_list, list_of_indices, value): current = nested_list # 遍历到倒数第二个索引,获取目标元素所在的父列表 for idx in list_of_indices[:-1]: current = current[idx] # 对目标位置赋值 current[list_of_indices[-1]] = value借助
operator与functools.reduce实现
利用operator.getitem配合functools.reduce快速定位父容器,写法更紧凑,适合熟悉函数式编程的场景:import operator from functools import reduce def nested_list_assignment(nested_list, list_of_indices, value): # 定位到目标元素的父容器 parent = reduce(operator.getitem, list_of_indices[:-1], nested_list) # 完成赋值 parent[list_of_indices[-1]] = value
总结来说,Python没有直接支持动态长度索引列表赋值的原生语法,但通过循环或者reduce+operator的组合即可轻松实现,无需依赖第三方库。
内容的提问来源于stack exchange,提问作者k huang
相关产品推荐
相关产品推荐

