for和while之间的区别

时间:2019-01-31 06:33:16

标签: python list for-loop data-structures while-loop

当我尝试进行循环以从列表中删除所有a时,这是我的代码:

list5 = ["a","b","a","b","a","b","c"]
def remove_values_from_list(_list, val):
        for val in _list:
            _list.remove(val)
remove_values_from_list(list5, "a")
print(list5)

返回:

["b","b","b"]

当我使用while而不是它返回时:

list5 = ["a","b","a","b","a","b","c"]
def remove_values_from_list(_list, val):
        while val in _list:
            _list.remove(val)
remove_values_from_list(list5, "a")
print(list5)



["b","b","b","c"]

有人可以解释一下为什么for循环不返回最后一个c吗?

2 个答案:

答案 0 :(得分:0)

您需要先修复for循环,它应该是:

def remove_values_from_list(_list, val):
        for _val in _list:
            if _val == val:
                _list.remove(val)
        print(_list)

输出:

['b', 'b', 'b', 'c']

,然后while循环也会这样:

def remove_values_from_list(_list, val):
    while(val in _list):
        _list.remove(val)
    print(_list)

remove_values_from_list(list5, "a")

输出:

['b', 'b', 'b', 'c']

编辑:

您应该像这样更改while循环:

while True:
    if val not in _list:
        break
    else:
        _list.remove(val)
print(_list)

编辑2:

感谢@Dukeling的收获:

使用for-loop遍历列表时,不能从列表中删除元素(连续的)。为此,我们可以像这样遍历它的副本:

def remove_values_from_list(_list, val):

    for _val in _list[:]:
        if _val == val:
            _list.remove(_val)
    print(_list)

list5 = ["a", "a"]

remove_values_from_list(list5, "a") 

输出:

[]

答案 1 :(得分:0)

这是因为您在for循环中使用val,并且函数接收的参数也称为val

尝试这样的事情:

def remove_values_from_list(_list, val):
    for v in _list:
        if v == val:
            _list.remove(v)

更有效的方法是:

def remove_values_from_list(_list, val):
    return list(filter(lambda x: x!=val, _list ))