簡體   English   中英

如何從列表中刪除項目?

[英]How to remove items from a list?

這是我到目前為止的代碼:

def remove(lst: list, pos: int):
    pass

def test_remove():
    lst = ['Turkey', 
       'Stuffing',
       'Cranberry sauce',
       'Green bean casserole',
       'Sweet potato crunch',
       'Pumpkin pie']

remove(lst, 2)

assert lst == ['Turkey', 
       'Stuffing',
       'Green bean casserole',
       'Sweet potato crunch',
       'Pumpkin pie',
       None]

lst = [5, 10, 15]
remove(lst, 0)
assert lst == [10, 15, None]

lst = [5]
remove(lst, 0)
assert lst == [None]

if __name__ == "__main__":
    test_remove()

在remove()中編寫代碼以刪除插槽pos中的項目,將其移出該項目以縮小間隙,並在最后一個插槽中保留值None。

關於我應該從哪里開始的任何想法?

給定一個列表lst中, pop(i)方法去除在該項目i “個索引超出lst

def remove(lst: list, pos: int):
    lst.pop(pos)

我在測試中也注意到,您希望在刪除項目時將None添加到列表的末尾。 不是這種情況。 None一個不應該是字符串列表中的一個項目,並且如果您從列表中刪除一個項目,則該項目消失了,但是其余項目保持不變,並且未添加任何其他內容。

如果確實要這樣做,只需將lst.append(None)添加到remove()函數的最后一行。

在remove()中編寫代碼以刪除插槽pos中的項目,將其移出該項目以縮小間隙,並在最后一個插槽中保留值None。

您可以使用listpop方法刪除該項目,然后將None附加到列表中。

def remove(lst: list, pos: int):
    lst.pop(pos)
    lst.append(None)

僅使用基本概念,我們就可以使用for循環:

def remove(lst: list, pos: int):
   for i in range(pos, len(lst)-1):
       lst[i] = lst[i+1]
   lst[-1] = None
   return lst

和一個測試:

remove([1,2,3,4,5,6], 2)
#[1, 2, 4, 5, 6, None]

請注意,使用@galfisher@R Sahu描述的內置方法會更加清楚。

暫無
暫無

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

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