我正在尝试反转列表的列表,以使存储在源列表中索引处的值成为新列表中的索引,原始索引现在将在该列表中存储。
例如,列表[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]]
要注意的一件事是,在invLists [1]而不是invLists [4]处插入了2。据我了解,使用-1作为索引应该返回列表中的最后一项,所以我不明白为什么它在这里没有这样做。排除其中newIndex设置为-1的条件语句会产生相同的结果。
尝试这个:
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句