python - 使用 "while"从另一个列表中删除一个列表的元素

标签 python python-3.x

我创建了一个简单的程序,它使用 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

如果您使用 break,则可以简化此操作,而不是使用 found 变量:

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

关于python - 使用 "while"从另一个列表中删除一个列表的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41731955/

相关文章:

python - 正则表达式查找文本文件中字符串的所有出现位置。如何?

python - 如何通过运行 'python ...' 从 shell 启动 ipython?

python - 如何从字符串中取出字母并将它们变成整数?

performance - 新项目 Python 3x PostgreSQL 9x 和 pg8000 1x DBAPI?

Python3通用继承层次结构

python - 将 pandas 的元组列转换为 MultiIndex

python - pycharm安装beautifulsoup后导入错误

Tornado 中页面上的 Python web 开发动态字段 id

python - 有没有办法将带有参数的函数 append 到列表中?

python-3.x - AWS Lambda 返回无法导入模块 'main' : No module named 'main' when modules are there