2016-01-23 115 views
0

我有这样一个列表返回相邻元素:[1, 3, 4, 5, 1] 和我想删除第一n元素,所以对于n = 3,我要返回列表,而从原来的列表中删除。所以我会有[1,3,4] 和我的原始列表现在[5, 1]删除并从列表中

什么是在Python中做到这一点的最佳方式?

+0

就解决它,谢谢! – Lana

回答

4

在Python 2.7中,它看起来像下面这样。只需提取部分列表并删除原始版本中不需要的部分即可。

lst = [1, 3, 4, 5, 1] 
new_lst = lst[:3] 
del lst[:3] 
print lst 
print new_lst 
2

如果要变更原始对象,可以使用[:]进行更改。例如:

>>> x = ['a','b','c','d','e'] 
>>> x[:], removed = x[3:], x[:3] 
>>> x 
['d', 'e'] 
>>> removed 
['a', 'b', 'c'] 

这工作,因为在右手边的条款,x[3:]x[:3],都被他们分配到目标左侧(x[:]removed)之前评估。

+0

我不会打扰'x [:]';分配给'x'本身具有相同的结果,并且垃圾收集原始列表中的延迟不太可能影响程序的整体性能。 – chepner

+1

@chepner:它没有相同的结果 - 想象一下'x'正被传递给一个函数。使用左侧的'x'只会重新绑定本地名称'x',它不会修改列表。 – DSM

1

这样的事情?

def pop_n(lst, n): 
    """ 
    Deletes the first *n* elements from *lst* and returns them. 
    """ 
    # validate inputs 
    # might want to use something other than isinstance() 
    if not isinstance(n, int) or n < 0: 
     raise ValueError("n must be a non-negative integer, not {}" 
         .format(n)) 

    # store the elements to return 
    ret = lst[:n] 
    # remove the elements from the original list 
    del lst[:n] 

    return ret 

编辑:这里是你的榜样案例演示。

>>> x = [1, 3, 4, 5, 1] 

>>> pop_n(x, 3) 
[1, 3, 4] 
>>> x 
[5, 1] 
0
>>> original = [1, 3, 4, 5, 1] 
>>> removed, original[:3] = original[:3],() 
>>> removed, original 
([1, 3, 4], [5, 1])