更改列表中的最后一个元素

2024-06-28 20:29:43 发布

您现在位置:Python中文网/ 问答频道 /正文

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

例如,其中一个列表[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

当Lists=[]、[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插入到InvList[1]而不是InvList[4]。据我所知,使用-1作为索引应该返回列表中的最后一项,所以我不明白为什么它在这里不这样做。排除newIndex设置为-1的条件语句会产生相同的结果


Tags: 列表indexlensolengthlistsatlist
3条回答

试试这个:

for i in range(len(Lists)):
    item = [-1] * len(Lists[i])
    for j in range(len(Lists[i])):
        item[Lists[i][j]] = j
    Lists[i] = item

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

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))]

您的代码有几个问题。一个小问题是索引,但隐藏起来的更大问题是浅拷贝与深拷贝。当你这样做的时候

invLists = Lists

这是肤浅的复制,您对InvList所做的任何更改也会影响列表。这就是“在索引1处插入2(应为索引4)”的原因

Python有复制模块,您可以对嵌套列表执行copy.deepcopy。以下是我对修正索引的看法;另外,您不必担心最后一个索引,因为您正在处理完全不同的两个列表

import copy
Lists = [[], [0, 1, 4, 3, 2], [0, 2, 4, 3, 1], [0, 3, 2, 1, 4], [0, 1, 4, 3, 2]]
def invertLists(Lists):

  invLists = copy.deepcopy(Lists)

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

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

  return invLists

invertLists(Lists)

相关问题 更多 >