python - 有效地从 python 中的列表中删除也在给定列表中的元素

标签 python list

所以我有两个列表和一个主列表。如果主列表中的元素出现在其他两个列表中的任何一个中,则应将其删除。

例子:

s1 = [1,2,3,4,7]
s2 = [3,4,5,6,20]
mainlist = [6,7,8,9,10,11,12,13,14,15]

因此,由于 mainList 包含元素 6 和 7,它们也存在于 s1 或 s2 中,因此应将其删除,结果应如下所示。

resultList = [8,9,10,11,12,13,14,15]

我的代码:

for j in mainlist[:]:
    if j in s1 or j in s2:
        mainlist.remove(j)

有没有不使用 for 循环的方法?我需要一种有效的方法来降低时间复杂度。谢谢!

最佳答案

你可以使用列表理解,它已经准备好解决这类问题了:

result = [x for x in mainlist if x not in s1 and x not in s2]

使用 list/set 操作,您可以执行以下操作之一

result = list(set(mainlist) - (set(s1) | set(s2)))  # remove the concat of s1&s2
result = list(set(mainlist) - set(s1) - set(s2))    # remove s1 and s2

关于python - 有效地从 python 中的列表中删除也在给定列表中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58780726/

相关文章:

python - 如何解决ModuleNotFoundError : No module named 'openpyxl.cell._writer' ?

python - while循环忽略打印?

Python - 带有 input() 的 If 语句在 def() 函数内部不起作用

Python - 如何从使用 OpenID 的网站请求页面

java - 排除一个特定值时 list.sort() 如何工作?

python - 尝试编写递归函数来迭代嵌套字典时出现 RecursionError

Python字典理解速度很慢

python - 在 python 中循环更新列表而不使用append 函数。

python - 计算列表中唯一字符串的数量? python 3

C# Unity 下拉菜单,在更改调用函数时,函数查询列表返回匹配的列表项