在python中迭代数据结构的正确方法是什么,同时从结构中删除元素?
我希望遍历someList结构,并确保访问列表中的所有项,只要它们在列表中,并在迭代时删除其中的一些项。但我不明白为什么有些数字会被跳过,以及我如何才能避免这种情况。在没有提前删除的情况下,确保列表中的每个元素都只显示一次。在本例中,我从未见过1、5和8
class someList():
def __init__(self):
self.list = list(range(0,10))
def getData(self):
for i in self.list:
print(i)
yield i
thing = someList()
for a in thing.getData():
print("we reached:", a)
if a % 2 == 1:
print("remove", a)
thing.list.remove(a)
elif (a * 2) in thing.list:
print("remove double a:", a, " a*2:", a * 2)
thing.list.remove(a*2)
print(thing.list)输出:
0
we reached: 0
remove double a: 0 a*2: 0
2
we reached: 2
remove double a: 2 a*2: 4
3
we reached: 3
remove 3
6
we reached: 6
7
we reached: 7
remove 7
9
we reached: 9
remove 9
[1, 2, 5, 6, 8]预期输出:
0
we reached: 0
remove double a: 0 a*2: 0
1
we reached: 1
remove 1
2
we reached: 2
remove double a: 2 a*2: 4
3
we reached: 3
remove 3
5
we reached: 5
remove 5
6
we reached: 6
7
we reached: 7
remove 7
8
we reached: 8
9
we reached: 9
remove 9
[2, 6, 8]注意:这与How to remove items from a list while iterating?不是一个问题,因为我不想在迭代之前过滤掉元素。
这两个修改条件只是示例,因为我确实迭代了一个图数据结构,使用了当前元素,并删除了一些与当前元素有特定关系的元素。
发布于 2019-12-17 00:20:47
正如其他人所说的,如果你试图在运行时修改列表,你将不会得到正确的初始化,所以使用另一个列表来存储你想要删除的内容,
class someList():
def __init__(self):
self.list = list(range(0,10))
def getData(self):
for i in self.list:
print(i)
yield i
thing = someList()
rem_list=[]
for a in thing.getData():
print("we reached:", a)
if a in rem_list:
pass
elif a % 2 == 1:
print("remove", a)
rem_list.append(a)
elif (a * 2) in thing.list:
print("remove double a:", a, " a*2:", a * 2)
rem_list.append(2*a)
thing.list=[x for x in thing.list if x not in rem_list]
print(thing.list) #outputs [2, 6, 8]使用rem_list存储要删除的成员,并且不在循环中检查它们,将会得到预期的结果。
https://stackoverflow.com/questions/59359637
复制相似问题