如何从列表中删除项目?

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。

关于我应该从哪里开始的任何想法?

给定一个列表 lstpop(i) 方法从 lst.

中删除第 i 个索引中的项目
def remove(lst: list, pos: int):
    lst.pop(pos)

我还注意到在您的测试中,您希望在删除项目时将 None 添加到列表的末尾。不是这种情况。 None 不应该是字符串列表中的项目,如果您从列表中删除一个项目,该项目就会消失,但其余项目保持不变,不会添加任何其他项目。

如果您确实想这样做,只需将 lst.append(None) 添加到 remove() 函数的最后一行。

Write code in remove() to remove the item in slot pos, shifting the items beyond it to close the gap, and leaving the value None in the last slot.

您可以使用 listpop 方法删除项目,然后将 None 添加到列表中。

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

只要使用基本概念,我们就可以使用for-loop:

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 所述,仅使用 built-in 方法会更清楚。