首页 > 解决方案 > 更改列表中的最后一个元素

问题描述

我正在尝试反转列表列表,以便存储在源列表中索引处的值成为新列表中的索引,原始索引现在将成为存储值。

例如,列表 [0,2,4,3,1] 之一将变为 [0,4,1,3,2]。

但是,我不知道如何修改列表中的最后一个元素。这是我到目前为止所拥有的:

def invertLists(Lists):

  invLists = Lists

  testIndex = 2
  print("List before: ", Lists[testIndex], "... length: ", len(Lists[testIndex]), '\n')

  for i in range(1, len(Lists)):
      for j in range(1, len(Lists[i])):
          newIndex = Lists[i][j]
          if(newIndex == len(Lists[i])):
              newIndex = -1
          else:
              invLists[i][newIndex] = j
          if i == testIndex:
              print("Insert ", j, " at index ", newIndex)
              print("List so far: ", invLists[i], '\n')

  return invLists

当列表 = [[], [0, 1, 4, 3, 2], [0, 2, 4, 3, 1], [0, 3, 2, 1, 4], [0, 1, 4, 3, 2]],输出如下:

List before:  [0, 2, 4, 3, 1] ... length:  5 

Insert  1  at index  2
List so far:  [0, 2, 1, 3, 1] 

Insert  2  at index  1 ##(should be index 4)##
List so far:  [0, 2, 1, 3, 1] 

Insert  3  at index  3
List so far:  [0, 2, 1, 3, 1] 

Insert  4  at index  1
List so far:  [0, 4, 1, 3, 1] 

(Every list):
[[], [0, 1, 4, 3, 2], [0, 4, 1, 3, 1], [0, 3, 2, 1, 4], [0, 1, 4, 3, 2]]

需要注意的一点是 2 插入到 invLists[1] 而不是 invLists[4]。据我了解,使用 -1 作为索引应该返回列表中的最后一项,所以我不明白为什么这里不这样做。排除 newIndex 设置为 -1 的条件语句会产生相同的结果。

标签: pythonlist

解决方案


问题出在您的循环范围内:

for i in range(1, len(Lists)):
    for j in range(1, len(Lists[i])):

Python 结构是零索引的。典型的迭代是

for i in range(len(Lists)):

或者

for idx, elem in enumerate(Lists):

您的关键问题是,对于长度为 N 的循环,您只处理N-1元素。

对于任何此类列表,这是一个简单得多的转换,my_list

[my_list.index(i) for i in range(len(my_list))]

推荐阅读