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

Python多维列表:如何不用链式索引实现类似splat运算符的索引赋值?

How to Assign to a Nested List Using an Index List (No Chained Indexing, No External Libraries)

Question

I have a 2D list a = [[1, 2, 3], [4, 5, 6]] and an index list index = [1, 2]. I want to assign a value to the element at the position specified by index using a syntax similar to a[*index] = 9 (or a[**index] = 9), but neither of these works. I'm looking for a way to do this without chained indexing like a[index[0]][index[1]] and without importing external libraries.

Answer

Great question! Python doesn’t natively support unpacking index lists directly in square brackets for assignment, but there are a couple of clean, built-in approaches to get the job done:

1. Manual Index Traversal (No Imports Needed)

This is the most straightforward method—we just walk through the nested list step-by-step to reach the parent of our target element, then assign using the final index:

a = [[1, 2, 3], [4, 5, 6]]
index = [1, 2]

# Navigate to the parent list of the target element
current_level = a
for idx in index[:-1]:
    current_level = current_level[idx]

# Assign the value to the final position
current_level[index[-1]] = 9

print(a)  # Output: [[1, 2, 3], [4, 5, 9]]

This works for any depth of nested lists, not just 2D—just adjust the index list to match the depth you need.

2. Use functools.reduce (Standard Library, No External Installs)

If you prefer a more concise approach, you can use Python’s built-in reduce function from the functools module (which is part of the standard library, so no extra packages required):

from functools import reduce

a = [[1, 2, 3], [4, 5, 6]]
index = [1, 2]

# Use reduce to navigate to the parent list
parent_list = reduce(lambda lst, idx: lst[idx], index[:-1], a)
parent_list[index[-1]] = 9

print(a)  # Output: [[1, 2, 3], [4, 5, 9]]

The reduce function applies the lambda repeatedly to each index (except the last one), starting from the top-level list a, until we reach the parent of our target element.

Both methods avoid chained indexing like a[index[0]][index[1]] and stick to Python’s built-in tools.

内容的提问来源于stack exchange,提问作者dylnan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:28:46