我有这样一个列表返回相邻元素:[1, 3, 4, 5, 1]
和我想删除第一n
元素,所以对于n = 3
,我要返回列表,而从原来的列表中删除。所以我会有[1,3,4]
和我的原始列表现在[5, 1]
。删除并从列表中
什么是在Python中做到这一点的最佳方式?
我有这样一个列表返回相邻元素:[1, 3, 4, 5, 1]
和我想删除第一n
元素,所以对于n = 3
,我要返回列表,而从原来的列表中删除。所以我会有[1,3,4]
和我的原始列表现在[5, 1]
。删除并从列表中
什么是在Python中做到这一点的最佳方式?
在Python 2.7中,它看起来像下面这样。只需提取部分列表并删除原始版本中不需要的部分即可。
lst = [1, 3, 4, 5, 1]
new_lst = lst[:3]
del lst[:3]
print lst
print new_lst
如果要变更原始对象,可以使用[:]
进行更改。例如:
>>> 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
)之前评估。
这样的事情?
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]
>>> original = [1, 3, 4, 5, 1]
>>> removed, original[:3] = original[:3],()
>>> removed, original
([1, 3, 4], [5, 1])
就解决它,谢谢! – Lana