所以我有两个列表和一个主列表。如果主列表中的元素出现在其他两个列表中的任何一个中,则应将其删除。
例子:
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/