Python多维列表:如何不用链式索引实现类似splat运算符的索引赋值?
Question
I have a 2D list
a = [[1, 2, 3], [4, 5, 6]]and an index listindex = [1, 2]. I want to assign a value to the element at the position specified byindexusing a syntax similar toa[*index] = 9(ora[**index] = 9), but neither of these works. I'm looking for a way to do this without chained indexing likea[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

