繁体   English   中英

使用“ while”从另一个列表中删除一个列表中的元素

[英]Remove elements of one list from another list using “while”

我创建了一个简单的程序,使用in方法至少两次将一个列表的元素从另一个列表中删除:

def remove(l_list,s_list):
    """Removes items of s_list from l_list and returns the rest"""
    res=[]
    for item in l_list:
        if item not in s_list:
            res.append(item)
    return res

我想用循环“ while”代替if not in s_list操作中的内容,并比较这些函数的复杂性。

所以,我做了下面的代码(不起作用):

def remove2(l_list,s_list):
    res=[]
    for item in l_list:
        found=False
        i=0
        while len(s_list)>i and not found:
            if item==s_list[i]:
                found=True
                if not found:
                    res.append(item)
            i+=1
    return res

例子:

>>> remove2([1,2,3],[1,2])
[3]
>>> remove2([1,2,3],[1])
[2,3]

我究竟做错了什么? 我的逻辑有什么问题?

您应该在while循环之后附加项目:

def remove2(l_list,s_list):
    res=[]
    for item in l_list:
        found=False
        i=0
        while len(s_list)>i and not found:
            if item==s_list[i]:
                found=True
            i+=1
        if not found:
            res.append(item)

    return res

而不是使用的found变量,如果你使用,你可以简化这个break

def remove2(l_list,s_list):
    res=[]
    for item in l_list:
        i=0
        while len(s_list)>i:
            if item==s_list[i]:
                break
            i+=1
        else:  
            # this else belongs to the while loop and is executed if and only if
            # the loop wasn't terminated by "break".
            res.append(item)

    return res

这里肯定存在逻辑缺陷:

        if item==s_list[i]:
            found=True
            if not found:
                res.append(item)
        i+=1

如果在该内部发现发现 永远不会为False,只需将其设置为True即可

另外,您是否需要进行艰苦的检查? 您可以“轻松” :-)使用单行命令执行此操作。 仅凭列表理解:

return [item for item in l_list if item not in s_list]

您也可以将它们变成集合,取差值,然后转换回列表:

return list(set(l_list).difference(set(s_list)))

暂无
暂无

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

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