【发布时间】:2017-01-08 13:20:41
【问题描述】:
我正在尝试通过代码删除循环中的每个元素来清除 python 列表
x=list(range(10000))
for i in x:
x.remove(i)
我认为在这段代码之后 x 必须是 [] ,而是只删除列表的每个第二个元素。 len(x)=5000 而不是 0。
为什么会这样?我究竟做错了什么。 谢谢
【问题讨论】:
标签: python python-2.7
我正在尝试通过代码删除循环中的每个元素来清除 python 列表
x=list(range(10000))
for i in x:
x.remove(i)
我认为在这段代码之后 x 必须是 [] ,而是只删除列表的每个第二个元素。 len(x)=5000 而不是 0。
为什么会这样?我究竟做错了什么。 谢谢
【问题讨论】:
标签: python python-2.7
original_list = list(range(1000))
remove_list_elements = []
for i in range(0, len(original_list), 2):
remove_list_elements.append(original_list[i])
[original_list.remove(i) for i in remove_list_elements]
print(len(original_list))
【讨论】:
如果您想实现一个列表对象,该对象在迭代时会自行擦除,这将相当容易:
class ErasingList(list):
"a list implemented as an iterator, iterating over it will .pop() items off"
def __iter__(self):
return self
def __next__(self):
try:
return self.pop(0)
#or self.pop() to take from the end of the list which is less intuitive but more efficient
except IndexError:
raise StopIteration
next = __next__ #vs2 compatibility.
x = ErasingList(range(100))
for i in x:
print(i)
print(x)
【讨论】:
a.remove(i) 搞砸了索引是我的猜测。
改为使用
a.clear()
这是清除列表的好方法。
【讨论】: