python 获取列表的前 x 个元素并删除它们

acm*_*6ou 2 python list

注意:我知道 StackOverflow 上可能已经有这个问题的答案,只是我找不到。

我需要这样做:

>>> lst = [1, 2, 3, 4, 5, 6]
>>> first_two = lst.magic_pop(2)
>>> first_two
[1, 2]
>>> lst
[3, 4, 5, 6]
Run Code Online (Sandbox Code Playgroud)

现在magic_pop不存在,我用它只是为了展示我需要的示例。有没有这样的方法magic_pop可以帮助我以Python方式完成所有事情?

Bar*_*mar 5

分两步进行。使用切片获取前两个元素,然后从列表中删除该切片。

first_list = lst[:2]
del lst[:2]
Run Code Online (Sandbox Code Playgroud)

如果你想要一个单行代码,你可以将它包装在一个函数中。

def splice(lst, start = 0, end = None):
    if end is None:
        end = len(lst)
    partial = lst[start:end]
    del lst[start:end]
    return partial

first_list = splice(lst, end = 2)
Run Code Online (Sandbox Code Playgroud)