有效地从python中的列表中移除元素,这些元素也在给定的列表中

2024-03-28 16:25:18 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我有两个列表和一个主列表。如果主列表中的元素存在于其他两个列表中,则应将其删除。你知道吗

示例:

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循环的?我需要一个有效的方法来降低时间复杂度。谢谢您!你知道吗


Tags: or方法代码in元素示例列表for
3条回答

也许您可以使用列表理解创建另一个列表

res = [i for i in test_list if i not in s1 and i not in s2]

或者使用filter() + lambda

res = filter(lambda i: i not in s1 and i not in s2, mainlist) 

或者使用for循环

for elem in mainlist:
   if elem in s1 or elem in s2:
      mainlist.remove(elem)

试试这个:

mainlist = list(set(mainlist) - (set(s1)|set(s2)))

这里我假设没有一个列表有重复的元素。你知道吗

你可以用时间和其他方法来比较。你知道吗

time_idx = time()
result = [x for x in mainlist if x not in s1 and x not in s2]
print(time() - time_idx)

0.00012612342834472656

time_idx = time()
mainlist = list(set(mainlist) - (set(s1)|set(s2)))
print(time() - time_idx)

0.00010609626770019531

由于这是一个小列表,因此改进是显著的。你知道吗

你可以使用列表理解,它可以很好地解决这类问题:

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

相关问题 更多 >