Python 从列表的开头和结尾弹出多个项目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24245057/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pop multiple items from the beginning and end of a list
提问by Ehsan88
Suppose I have a list of items like this:
假设我有一个这样的项目列表:
mylist=['a','b','c','d','e','f','g','h','i']
I want to pop two items from the left (i.e. aand b) and two items from the right (i.e. h,i). I want the most concise an cleanway to do this. I could do it this way myself:
我想从左侧(即a和b)弹出两个项目,从右侧(即h,i)弹出两个项目。我想要最简洁干净的方式来做到这一点。我自己可以这样做:
for x in range(2):
mylist.pop()
mylist.pop(0)
Any other alternatives?
还有其他选择吗?
采纳答案by bold
From a performance point of view:
从性能来看:
mylist = mylist[2:-2]anddel mylist[:2];del mylist[-2:]are equivalent- they are around 3 times faster than the first solution
for _ in range(2): mylist.pop(0); mylist.pop()
mylist = mylist[2:-2]并且del mylist[:2];del mylist[-2:]是等价的- 它们比第一个解决方案快 3 倍左右
for _ in range(2): mylist.pop(0); mylist.pop()
Code
代码
iterations = 1000000
print timeit.timeit('''mylist=range(9)\nfor _ in range(2): mylist.pop(0); mylist.pop()''', number=iterations)/iterations
print timeit.timeit('''mylist=range(9)\nmylist = mylist[2:-2]''', number=iterations)/iterations
print timeit.timeit('''mylist=range(9)\ndel mylist[:2];del mylist[-2:]''', number=iterations)/iterations
output
输出
1.07710313797e-06
1.07710313797e-06
3.44465017319e-07
3.44465017319e-07
3.49956989288e-07
3.49956989288e-07
回答by Aaron Hall
You could slice out a new list, keeping the old list as is:
您可以切出一个新列表,保持旧列表不变:
mylist=['a','b','c','d','e','f','g','h','i']
newlist = mylist[2:-2]
newlistnow returns:
newlist现在返回:
['c', 'd', 'e', 'f', 'g']
You can overwrite the reference to the old list too:
您也可以覆盖对旧列表的引用:
mylist = mylist[2:-2]
Both of the above approaches will use more memory than the below.
以上两种方法都会比下面的方法使用更多的内存。
What you're attempting to do yourself is memory friendly, with the downside that it mutates your old list, but popleftis not available for lists in Python, it's a method of the collections.dequeobject.
您自己尝试做的是内存友好的,缺点是它会改变您的旧列表,但popleft不适用于 Python 中的列表,它是collections.deque对象的一种方法。
This works well in Python 3:
这在 Python 3 中运行良好:
for x in range(2):
mylist.pop(0)
mylist.pop()
In Python 2, use xrange and pop only:
在 Python 2 中,仅使用 xrange 和 pop:
for _ in xrange(2):
mylist.pop(0)
mylist.pop()
Fastest way to delete as Martijn suggests, (this only deletes the list's reference to the items, not necessarily the items themselves):
Martijn 建议的最快删除方法,(这只会删除列表对项目的引用,不一定是项目本身):
del mylist[:2]
del mylist[-2:]
回答by zer0uno
First 2 elements: myList[:2]
Last 2 elements: mylist[-2:]
前 2 个元素:myList[:2]
最后 2 个元素:mylist[-2:]
So myList[2:-2]
所以 myList[2:-2]
回答by Martijn Pieters
If you don't want to retain the values, you could delete the indices:
如果您不想保留这些值,您可以删除索引:
del myList[-2:], myList[:2]
This does still require that all remaining items are moved up to spots in the list. Two .popleft()calls do require this too, but at least now the list object can handle the moves in one step.
这仍然需要将所有剩余的项目向上移动到列表中的位置。两次.popleft()调用也需要这样做,但至少现在列表对象可以一步处理移动。
No new list object is created.
不会创建新的列表对象。
Demo:
演示:
>>> myList = ['a','b','c','d','e','f','g','h','i']
>>> del myList[-2:], myList[:2]
>>> myList
['c', 'd', 'e', 'f', 'g']
However, from your use of popleftI strongly suspect you are, instead, working with a collections.dequeue()objectinstead. If so, *stick to using popleft(), as that is far more efficient than slicing or delon a list object.
但是,从您的使用来看,popleft我强烈怀疑您是在使用collections.dequeue()对象。如果是这样,*坚持使用popleft(),因为这比切片或del列表对象更有效。
回答by Chris Hubley
To me, this is the prettiest way to do it using a generator function:
对我来说,这是使用生成器函数的最漂亮的方法:
>> mylist=['a','b','c','d','e','f','g','h','i']
>> newlist1 = [mylist.pop(0) for idx in range(1)]
>> newlist2 = [mylist.pop() for idx in range(1)]
That will pull the first two elements from the beginning and the last two elements from the end of the list. The remaining items stay in the list.
这将从列表的开头拉出前两个元素,从列表的末尾拉出最后两个元素。其余项目保留在列表中。

