遍历一个集合可能进入无限循环的原因是在循环中修改了集合的大小,导致循环条件无法结束。以下是解决方法的示例代码:
collection = [1, 2, 3, 4, 5]
for item in collection[:]: # 使用切片操作遍历原集合的一个副本
if item == 3:
collection.remove(item) # 在循环中修改集合的大小
print(collection) # 输出 [1, 2, 4, 5]
collection = [1, 2, 3, 4, 5]
index = 0
while index < len(collection):
item = collection[index]
if item == 3:
collection.remove(item) # 在循环中修改集合的大小
else:
index += 1
print(collection) # 输出 [1, 2, 4, 5]
以上两种方法都是在遍历集合之前创建了集合的副本或使用索引来控制循环,以避免在循环中修改集合的大小而导致无限循环。