如何过滤 y 不包含在另一个列表中的元组(x,y)列表?

use*_*685 0 python list python-3.x

我有一个带有 (string,int) 对的元组列表。

我也有一个 int 的列表。

我想通过以下伪代码过滤元组列表:

l1 = list of touples(string,int)
l2 = list of int's

for tuple in l1:
   if tuple(int) is in l2
      remove tuple from l1
Run Code Online (Sandbox Code Playgroud)

例如,让我们说

l1=[("one",1),("two",5),("three",8),("bla",11)]

l2=[1,8]
Run Code Online (Sandbox Code Playgroud)

输出将是:

[("two",5),("bla",11)]
Run Code Online (Sandbox Code Playgroud)

希望这很清楚。

Ami*_*ron 7

您应该创建一组过滤器值,然后使用列表理解来构建新列表:

l1 = [("one",1),("two",5),("three",8),("bla",11)]
l2 = [1,8]
# Make a set for efficient 
s2 = set(l2)
# List comprehension for including only tuples where integer is not in s2 (l2)
l3 = [t for t in l1 if t[1] not in s2]

print(l3)
Run Code Online (Sandbox Code Playgroud)