使用索引列表引用嵌套列表中的项目
Reference an item in a nested list with a list of indexes
我在 Python 中有一个任意嵌套的列表,我想修改该列表中的一个项目。为此,我想使用一个索引列表。它类似于索引嵌套列表 list[0][2][1]
的传统方式,但我希望将这些相同的索引存储在像 [0, 2, 1]
这样的列表中
例如一段关于它如何工作的伪代码:
nestedList = [[0,1],[2,3]]
indexList = [1, 0]
replacement = 6
nestedList = ReplaceItemInNestedList(nestedList, indexList, replacement)
nestedList: [[0,1],[6,3]]
到目前为止,我只设法创建了一种访问项目的方法,但没有修改它。其代码如下。
for i in indexList:
nestedList = nestedList[i]
# nestedList will equal to item when loop has finished.
肯定有办法修改一个项目,因为访问一个项目是如此简单,但我找不到方法。两年前,here 提出了几乎相同的问题,但答案需要导入库。是否可以不导入库?
提前致谢!
所以,是的,您所要做的就是遍历所有索引,除了最后一个索引并使用它来执行替换:
def ReplaceItemInNestedList(nestedList, indexList, replacement):
for i in indexList[:-1]:
nestedList = nestedList[i]
lastIndex = indexList[-1]
nestedList[lastIndex] = replacement
nestedList = [[0,1],[2,3]]
indexList = [1, 0]
replacement = 6
ReplaceItemInNestedList(nestedList, indexList, replacement)
print(nestedList)
按要求输出
您在 indexList
中的最后一项是最内层列表中该项的索引。因此,您需要遍历 indexlist
中的倒数第二个元素来获得最终列表。为此,请执行:
finalList = nestedList
for index in indexList[:-1]:
finalList = finalList[index]
finalList[indexList[-1]] = replacement
我在 Python 中有一个任意嵌套的列表,我想修改该列表中的一个项目。为此,我想使用一个索引列表。它类似于索引嵌套列表 list[0][2][1]
的传统方式,但我希望将这些相同的索引存储在像 [0, 2, 1]
例如一段关于它如何工作的伪代码:
nestedList = [[0,1],[2,3]]
indexList = [1, 0]
replacement = 6
nestedList = ReplaceItemInNestedList(nestedList, indexList, replacement)
nestedList: [[0,1],[6,3]]
到目前为止,我只设法创建了一种访问项目的方法,但没有修改它。其代码如下。
for i in indexList:
nestedList = nestedList[i]
# nestedList will equal to item when loop has finished.
肯定有办法修改一个项目,因为访问一个项目是如此简单,但我找不到方法。两年前,here 提出了几乎相同的问题,但答案需要导入库。是否可以不导入库?
提前致谢!
所以,是的,您所要做的就是遍历所有索引,除了最后一个索引并使用它来执行替换:
def ReplaceItemInNestedList(nestedList, indexList, replacement):
for i in indexList[:-1]:
nestedList = nestedList[i]
lastIndex = indexList[-1]
nestedList[lastIndex] = replacement
nestedList = [[0,1],[2,3]]
indexList = [1, 0]
replacement = 6
ReplaceItemInNestedList(nestedList, indexList, replacement)
print(nestedList)
按要求输出
您在 indexList
中的最后一项是最内层列表中该项的索引。因此,您需要遍历 indexlist
中的倒数第二个元素来获得最终列表。为此,请执行:
finalList = nestedList
for index in indexList[:-1]:
finalList = finalList[index]
finalList[indexList[-1]] = replacement