使用函数`pop`通过`while`循环从列表中删除元素

时间:2018-03-10 09:50:42

标签: python list for-loop while-loop pop

x = list(range(10))
print(x)
print(len(x))

while x != []: # run this loop if the list x not equal to [] is true
    for i in range(len(x)): # the first index is i =0
        x.pop(i)  #removes the element positioned at index i = 0 from the list x
print(x) 

Python不会返回我所寻求的内容。

这里有什么问题?

无解决方案

欣赏提示。

2 个答案:

答案 0 :(得分:0)

在索引0删除元素后,现在索引为0的元素实际上是索引1处的元素,因为所有元素都是“向前移动”。所以,你不需要在里面进行for循环,你只需要在开始的时候调用x.pop(0)

因此,代码看起来像:

x = list(range(10))
while x:                                                 #(equivalent to `x != []`)
    x.pop(0)

x作为[]完成。

请注意,弹出第一个元素实际上是O(n)复杂度(与弹出最后一个O(1)相比)。因此,如果您正在寻找效率,可以使用double-ended queue允许使用popleft()(相当于pop(0))但O(1)

所以实现它只会是:

import collections
x = collections.deque(range(10))
while x:
    x.popleft()

xdeque([]),但如有必要,您可以转换回list()的列表。

答案 1 :(得分:0)

由于您基本上想要左键弹出,因此您可能需要考虑使用deque而不是list

from collections import deque
x = deque(range(10))

while x:
  x.popleft()

print(x)  # deque([])