避免对自身进行迭代的一种常见解决方法是创建一个副本,然后对副本进行迭代。以下是一些常见的示例代码:
lst = [1, 2, 3, 4, 5]
lst_copy = lst[:]
for item in lst_copy:
print(item)
lst = [1, 2, 3, 4, 5]
lst_copy = list(lst)
for item in lst_copy:
print(item)
lst = [1, 2, 3, 4, 5]
lst_copy = lst.copy()
for item in lst_copy:
print(item)
这些方法都会创建一个新的列表,该列表与原始列表具有相同的元素,但是它们是独立的,并且可以安全地对副本进行迭代,而不会影响原始列表。
下一篇:避免多层嵌套的for循环