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



我有一个带有(字符串,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

例如,假设

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

输出将是:

[("two",5),("bla",11)]

希望这是清楚的。

您应该创建一组筛选器值,然后使用列表推导式来构造新列表:

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)
output = [(key, value) for key, value in l1 if value not in set(l2)]
print(output)

输出:

[('two', 5), ('bla', 11)]

我会使用过滤器或列表推导,如下所示:

filtered_tuples = [t for t in l1 if t[1] not in l2]

如果您觉得使用 for 循环更舒服,您可以执行以下操作:

filtered_tuples = []
for t in l1:
if t[1] not in l2:
filtered_tuples.append(t)

每当有可迭代对象时,都可以使用 in 关键字检查对象是否位于该可迭代对象中的某个位置。

一种功能方法是使用filter内置函数

filter(lambda x: x[1] in l2, l1)

这将返回一个迭代器而不是一个列表,尽管对于足够大的l1您可能无论如何都希望使用生成器/迭代器

最新更新