簡體   English   中英

在 Python 中的其他列表中刪除列表元素

[英]Deleting elements of lists, within other lists in Python

在做一些與列表和函數相關的 Python 練習時,我遇到了以下代碼:

list = [0, 1, 2, 3, 4]


def function (lst):
    del lst[lst[3]]
    return lst


print (function (list))

導致以下 output:

[0, 1, 2, 4]

但是,在以下代碼中,發生了一些不同的事情:

list = [0, 1, 4, 9, 16]


def function (lst):
    del lst[lst[3]]
    return lst


print (function (list))

它輸出此錯誤:

Traceback (most recent call last):
  File "...", line 9, in <module>
    print (function (list))
  File "...", line 5, in function
    del lst[lst[3]]
IndexError: list assignment index out of range

Process finished with exit code 1

在這種情況下,它只“允許”我刪除直到元素 [2],結果為: [0, 1, 4, 9]

在這種情況下,我不太了解列表中列表的用法,以及為什么有時它會像只有一個列表一樣執行; 有時,“內部”列表的長度較小。 如果有人能澄清這個新手問題,我將不勝感激。

提前謝謝你!

在第二種情況下,您會看到 Index out of range 錯誤,因為 del 方法試圖在列表中查找第 9 個元素。 就像這樣:

list = [0, 1, 4, 9, 16]


def function (lst):
    del lst[lst[3]] # Here, python first evaluates lst[3] -> 3rd element from list. Which is 9. And then, evaluates del lst[9] -> tries to find 9th element in list, which doesn't exist. 
    return lst


print (function (list))

當你這樣做時:

list = [0, 1, 4, 9, 16]


def function (lst):
    del lst[lst[2]] # lst[2] evaluates to 2nd element from list, which is 4, and del lst[4] evaluates to 4th element in the list, which is 16 and deletes 16 from list.
    return lst


print (function (list))

這是因為 lst[lst[3]] 表示 go 到 index = lst[3]。 例如在你的第一個例子中, lst[3] = 3 所以 lst[lst[3]] = lst[3] 但在你的第二個例子中 lst[3] = 9 所以 lst[lst[3]] = lst[9]但是你的數組的長度是 5 所以這就是為什么你有一個索引超出范圍異常。

list = [0, 1, 2, 3, 4]


def function (lst):
    del lst[lst[3]]. # ok to do this because lst[3] has the value of 3
                     # so basically you are deleting the 4th item
    return lst

print (function (list))
list = [0, 1, 4, 9, 16]


def function (lst):
    del lst[lst[3]]. # here lst[3] is 9 and there are no 10th items in the list
    return lst


print (function (list))

您實際上在這里所做的是根據列表中的值索引您的列表。

因此,如果list = [0, 1, 4, 9, 16]list[3]等於9 (第 4 個元素)。

如果您調用list[list[3]]您實際上是在調用list[9] ,這超出了范圍。

如果您需要刪除列表索引 3 處的數字;

list = [0, 1, 4, 9, 16]
def function (lst):
    del lst[3]
    return lst

print (function(list))
[0, 1, 4, 16]

如果您執行lst[lst[3]] ,首先它會在 lst 索引 3 處找到數字,其中值為 9,刪除list[9]會給出索引超出范圍錯誤,因為 lst 的長度為 5 :

暫無
暫無

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

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