How to remove an item while iterating over a list?

我怕爱的太早我们不能终老 提交于 2020-01-02 16:09:12

问题


My code looks like this:

def nue(li):
    for i in li:
        li.remove(i)
    print(li)

li = [1, 2, 3]

nue(li)

However, running this results in:

>>> [2]

More generally, how do I remove the i-th position on a list while iterating over the list (for reasons it failed some test in a nested loop or something like that)?


回答1:


you can do like this

def nue(li):
    for i in li[:]:
        li.remove(i)
    print(li)

li = [1, 2, 3]

nue(li)

li[:] will clone original li




回答2:


Try list comprehension:

def remi(slist, i):    # remi means REMove I
    return [slist[j] 
            for j in range(len(slist))
            if j != i]

print(remi ([1,2,3,4], 2))

Output:

[1, 2, 4]



回答3:


Why not just use a list comprehension instead of removing items from an existing list?

old_list = [1,2,3,4,5]
li = [1,2,3]
new_list = [i for i in old_list if i not in li]

If you don't want to use a list comprehension you can try the filter function

old_list = [1,2,3,4,5]
li = [1,2,3]
new_list = list(filter(lambda x: x not in li, old_list))



回答4:


You might want to consider going over the array in reverse. The following code demonstrates three functions that do the same thing. All are called prune and are interchangeable. By looking at an array in reverse order, you avoid changing the index of values you will examine in the future.

#! /usr/bin/env python3
def main():
    array = list(range(20))
    print(array)
    prune(array, lambda value: value % 3)
    print(array)


def prune(array, del_condition):
    for index, value in reversed(tuple(enumerate(array))):
        if del_condition(value):
            del array[index]


def prune(array, del_condition):
    for index in range(len(array) - 1, -1, -1):
        value = array[index]
        if del_condition(value):
            del array[index]


def prune(array, del_condition):
    for index in reversed(range(len(array))):
        if del_condition(array[index]):
            del array[index]


if __name__ == '__main__':
    main()


来源:https://stackoverflow.com/questions/48327207/how-to-remove-an-item-while-iterating-over-a-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!