简体   繁体   English

递归迭代递减列表

[英]Recursively iterate over decreasing list

I want to recursively iterate over a list without considering the items i'm deleting我想递归遍历列表而不考虑我要删除的项目

Code:代码:

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

Now the removal works but the for loop doesn't know that the items are deleted, how do i make it so that the updated list is considered every time?现在可以删除了,但是 for 循环不知道项目已被删除,我该怎么做才能每次都考虑更新的列表?

One way to avoid the issue you've encountered is to iterate over the list in reverse.避免您遇到的问题的一种方法是反向迭代列表。 That way, the current index is independent of deletions for elements with greater indices.这样,当前索引独立于具有更大索引的元素的删除。

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]

Another way to remove elements, if you don't need to modify the list in-place, is to use a list comprehension combined with a condition ( if x != 'a' ).如果不需要就地修改列表,另一种删除元素的方法是结合使用列表理解和条件( if x != 'a' )。

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

Additionally, Python has a filter function, which takes a function for specifying elements to drop.此外,Python 有一个filter function,它需要一个 function 来指定要丢弃的元素。

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

Try this:试试这个:

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)

Output: Output:

['(', ')']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM