我正在迭代两个列表,如下所示:
list1 = [z]
list2 = [z-t,z-s,s-a,a-n, g-z]
for e in list1:
for t in list2:
# if item from list2 contains item from list1 (before "-")
# remove the item from list2 and append part after "-" to list1
# iterate again until no change is made or list2 is empty
我无法解决的问题是,当我从 list2 中删除该项目时,它会转到下一个项目,而我无法阻止它。例如
list2 = [z-t,z-s,s-a....]
^ removing this while iterating
next iteration jumps over one item
list2 = [z-s, s-a,...]
^ this is where I am second iteration
list2 = [z-s, s-a,...]
^ this is where I want to be
有什么办法可以做到这一点吗?
最佳答案
有几种方法可以实现这一点,其中一种是向后迭代列表,即
for e in list1:
for t in list2[::-1]: # This iterates over the list backwards
# Do your check
# Remove the element
如果你需要向前处理它,你可以迭代一个副本,这样你就可以在迭代初始内容的同时改变原始列表,即
for e in list1:
for t in list2[:]: # The [:] syntax feeds you your data via a new list.
# Do your check
# Remove the element, and not worry about mutating the original list length
关于python - 删除和添加项目到迭代列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29659016/