问题描述
some_list = [1,2,3,4]
another_list = [1,2,3,4]
为idx,枚举项目(some_list):
del some_list [idx]
another_list:
another_list.remove(item)
当我列出列表的内容
>>> some_list
[2,4]
>>> another_list
[2,4]
t支持修改一个 list
而迭代它,正确的方法是迭代列表的副本,而不是(所以请不要downvote)。但是我想知道幕后究竟发生了什么,也就是说为什么上面的代码片段的输出 [2,4]
?
class CustomIterator(object):
def __init __(self,seq):
self.seq = seq
self.idx = 0
def __iter __(self):
return self
$ b $ def __next __(self):
print( 'self.idx)
for idx,enumerate(self.seq)中的项:
if id == self.idx:
print(idx,' - - >',item)
else:
print(idx,'',item)
try:
nxtitem = self.seq [self.idx]
除了IndexError:
提高StopIteration
self.idx + = 1
返回nxtitem
下一个=然后在你想检查的列表中使用它: $ b
$ p
$ b $
$ bsome_list = [1,2,3,4]
为idx,枚举中的项(CustomIterator(some_list)):
del some_list [idx]
这个例子说明了这种情况:
给下一个元素:0
0 ---> 1
1 2
2 3
3 4
给下一个元素:1
0 2
1 ---> 3
2 4
给下一个元素:2
0 2
1 4
它只适用于序列。这对于映射或集合来说更为复杂。
I'm iterating a list as follows:
some_list = [1, 2, 3, 4] another_list = [1, 2, 3, 4] for idx, item in enumerate(some_list): del some_list[idx] for item in another_list: another_list.remove(item)
When I print out the contents of the lists
>>> some_list [2, 4] >>> another_list [2, 4]
I'm aware that Python doesn't support modifying a
list
while iterating over it and the right way is to iterate over copy of list instead (so please don't downvote). But I want to know what exactly happens behind the scenes i.e. Why is the output of the above snippet[2, 4]
?解决方案You can use a self-made iterator that shows (in this case
class CustomIterator(object): def __init__(self, seq): self.seq = seq self.idx = 0 def __iter__(self): return self def __next__(self): print('give next element:', self.idx) for idx, item in enumerate(self.seq): if idx == self.idx: print(idx, '--->', item) else: print(idx, ' ', item) try: nxtitem = self.seq[self.idx] except IndexError: raise StopIteration self.idx += 1 return nxtitem next = __next__ # py2 compat
Then use it around the list you want to check:
some_list = [1, 2, 3, 4] for idx, item in enumerate(CustomIterator(some_list)): del some_list[idx]
This should illustrate what happens in that case:
give next element: 0 0 ---> 1 1 2 2 3 3 4 give next element: 1 0 2 1 ---> 3 2 4 give next element: 2 0 2 1 4
It only works for sequences though. It's more complicated for mappings or sets.
这篇关于当您尝试在遍历它时删除列表元素会发生什么情况的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!