我目前遇到的情况是这样的:
for element in some_list:
if(some_condition==True):
some_list.clear()
some_list.append(new_elements)
但是,这给了我一些奇怪的行为。 for 循环仅运行与 some_list 的原始长度相同的迭代次数。
如何解决这个问题,以便我可以对列表进行修改,并且仍然使循环正常运行?
这是我的实际代码,以防您想查看。它是检查图之间同构的算法的一部分。
if (len(v_in_g1_with_color) + len(v_in_g2_with_color)) >= 4:
for vertex2 in v_in_g2_with_color:
if(sorted(refinement2[0][0].values()) == sorted(refinement2[1][0].values())):
v += 1
vertex_to_be_checked = list((colours1.keys()))[v]
v_in_g2_with_color.clear()
for key, value in colours2.items():
if value == colours1[vertex_to_be_checked]:
v_in_g2_with_color.append(key)
continue
我还没有想出解决办法。但预期的行为是能够修改列表并迭代列表的新修改版本,而不是旧版本。
使用 for 循环迭代列表时修改列表可能会导致意外行为。当您调用
some_list.clear()
时,循环的内部索引前进到清除元素之后应该存在的下一个元素。但是,由于列表现在为空,因此循环终止。
您可以使用列表理解:
v_in_g2_with_color = [key for key, value in colours2.items() if value == colours1[vertex_to_be_checked]]
这会创建一个新列表,其中包含
colours2
中满足条件的元素,从而有效地过滤和修改列表,而不影响原始循环。