删除并添加项目到迭代列表

时间:2015-04-15 19:23:27

标签: python python-3.x

我正在迭代两个列表:

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

有没有办法做到这一点?

1 个答案:

答案 0 :(得分:1)

有几种方法可以实现这一点,一种是在列表上向后迭代,即

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