You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

已知深度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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 10:39:33