已知深度n的嵌套列表,如何通过重复索引0访问顶层元素?
嵌套列表重复索引访问的实现方案
方法一:循环迭代(最直观可靠)
直接通过循环逐层取第一个元素,重复n次就能拿到目标内容,这种方式可读性强,不容易出问题。
示例代码:
triple_nested_list = [[[{'foo': ['bar']}]]] n = 3 target = triple_nested_list for _ in range(n): target = target[0] print(target) # 输出: {'foo': ['bar']}
方法二:用functools.reduce简化写法
借助reduce函数连续执行索引操作,把每次的结果作为下一次的输入,代码更简洁。
示例代码:
from functools import reduce triple_nested_list = [[[{'foo': ['bar']}]]] n = 3 target = reduce(lambda current, _: current[0], range(n), triple_nested_list) print(target) # 输出: {'foo': ['bar']}
你之前的尝试失败原因
你写的triple_nested_list[[e] * n]是把一个包含n个[0]的嵌套列表当作索引,但Python的列表只接受整数、切片或布尔数组作为索引,这种写法会触发TypeError,自然无法正常运行。
内容的提问来源于stack exchange,提问作者iskandarblue
相关产品推荐
相关产品推荐

