python - 删除和添加项目到迭代列表

标签 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

有什么办法可以做到这一点吗?

最佳答案

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

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/

相关文章:

python - 在组中找到最频繁的观察

python-3.x - 构建顺序模型时如何修复 'the added layer must be an instance of class layer'?

opencv - Python 导入错误 : undefined symbol: _Z33parallel_pthreads_set_threads_numi

python - 在 Pandas 中反转 'one-hot' 编码

python - Django:从中间件获取页面标题

python - 如何在python的单行中编写if和else

Python3 - 将枚举转换为不同的数据类型

python-3.x - 如何修复Python3.7.1中的 "No module named '编码?

python - 引用或复制

python - 读取大型制表符分隔文件分块时出现异常