簡體   English   中英

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

[英]Changing the last element in a list

我正在嘗試反轉列表列表,以便存儲在源列表索引處的值成為新列表中的索引,原始索引現在將成為存儲值。

例如,列表 [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 的條件語句會產生相同的結果。

問題出在您的循環范圍內:

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

嘗試這個:

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

您的代碼有幾個問題。 一個小問題是索引,但更大的問題是淺拷貝與深拷貝。 當你做

invLists = Lists

那是淺拷貝,您對 invLists 所做的任何更改也會影響 Lists。 這就是“在索引 1 ##(應該是索引 4)## 處插入 2”的原因

Python 有 copy 模塊,你可以對嵌套列表執行 copy.deepcopy。 這是我通過修復您的索引的看法,而且您不必擔心最后一個索引,因為您正在處理完全 2 個不同的列表。

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM