【问题标题】:Recursively iterate over decreasing list递归迭代递减列表
【发布时间】:2021-02-09 23:00:26
【问题描述】:

我想递归迭代一个列表而不考虑我要删除的项目

代码:

list_example = ['a', 'a', 'a', 'a', '(', 'a', 'a', ')']
for index, item in enumerate(list_example):
    if item == 'a':
        del list_example[index]

现在删除工作正常,但 for 循环不知道项目已被删除,我该如何制作以便每次都考虑更新的列表?

【问题讨论】:

  • 使用 while 循环而不是 for 循环并维护自己的索引
  • 什么是“递归迭代”?我在这里看不到任何递归。
  • 如果您的问题出在索引上,您可以在每次删除元素时将索引移动 1

标签: python recursion iteration


【解决方案1】:

避免您遇到的问题的一种方法是反向迭代列表。这样,当前索引与删除具有更大索引的元素无关。

list_example = ['a', 'a', 'a', 'a', '(', 'a', 'a', ')']
for index in reversed(range(len(list_example))):
    if list_example[index] == 'a':
        del list_example[index]

如果您不需要就地修改列表,另一种删除元素的方法是使用列表推导结合条件 (if x != 'a')。

list_example = ['a', 'a', 'a', 'a', '(', 'a', 'a', ')']
list_example = [x for x in list_example if x != 'a']

另外,Python 有一个filter 函数,它接受一个指定要删除的元素的函数。

list_example = ['a', 'a', 'a', 'a', '(', 'a', 'a', ')']
list_example = list(filter(lambda x: x != 'a', list_example))

【讨论】:

  • reversed(range(len(list_example))) 可能比range(len(list_example) - 1, -1, -1) 更具可读性?
  • @fountainhead,我同意并更新了答案。谢谢!
  • 另一种删除元素的方法,如果您确实需要就地修改列表,请使用:list_example[:] = [x for x in list_example if x!= 'a']
【解决方案2】:

试试这个:

list_example = ['a', 'a', 'a', 'a', '(', 'a', 'a', ')']
for item in reversed(list_example):
    if (item == 'a'):               # Found an 'a' while going right-to-left
        list_example.remove('a')    # Remove the first 'a' going from left-to-right
print (list_example)

输出:

['(', ')']

【讨论】:

    猜你喜欢
    • 2014-12-23
    • 2022-01-15
    • 2011-11-14
    • 2012-10-17
    • 2019-12-10
    • 2022-11-11
    • 2012-04-26
    • 2012-01-23
    • 2021-11-09
    相关资源
    最近更新 更多