首页 > 解决方案 > 如何获取两个元组列表中存在的不常见元组列表

问题描述

我有两个列表 l1 和 l2 ,其中包含里面的元组,我需要用 l2 中存在的元组过滤掉 l1 中的元组。这个怎么做?

l1=[('a','b','c','d','e'),('t','y','u','i','o'),('q','s','a','e','r'),('t','f','e','w','l')]
l2=[('a','r'),('l','f')]
output=[('a','b','c','d','e'),('t','y','u','i','o')]


k=0
p=0
filter=[]
for i in l1:
    for j in l2:
        if i[k]!=j[p]:
            ss=i
            filter.append(ss)
            k+=1
            p+=1

标签: pythonlisttuplesintersection

解决方案


l2首先转换为集合列表会更有效,以便您可以在线性时间内执行子集检查:

s2 = list(map(set, l2))
output = [l for l in l1 if not any(s.issubset(l) for s in s2)]

output变成:

[('a', 'b', 'c', 'd', 'e'), ('t', 'y', 'u', 'i', 'o')]

推荐阅读