Python:过滤元组

标签 python filter tuples

我有两个元组列表。我想要一个新列表,其中包含 l2 的每个成员和 l1 的每个成员,但不以 l2 中的相同元素开头。

我使用了 for 循环,我的输出没问题。

我的问题是:如何使用过滤功能或列表理解?

def ov(l1, l2):

    l3=l1.copy()    
    for i in l2:

        for j in l1:

            if i[0]==j[0]:
                l3.pop(l3.index(j))

    print (l3+l2)            

ov([('c','d'),('c','e'),('a','b'),('a', 'd')], [('a','c'),('b','d')])

输出是:

[('c', 'd'), ('c', 'e'), ('a', 'c'), ('b', 'd')]

最佳答案

如果我理解正确,这应该是直接的解决方案:

>>> l1 = [('c','d'),('c','e'),('a','b'),('a', 'd')]                                                                               
>>> l2 = [('a','c'),('b','d')]                                                                                                    
>>>                                                                                                                               
>>> starters = set(x for x, _ in l2)                                                                                              
>>> [(x, y) for x, y in l1 if x not in starters] + l2                                                                             
[('c', 'd'), ('c', 'e'), ('a', 'c'), ('b', 'd')]

这可以推广到使用更长的元组 extended iterable unpacking .

>>> starters = set(head for head, *_ in l2)                                                                                             
>>> [(head, *tail) for head, *tail in l1 if head not in starters] + l2                                                            
[('c', 'd'), ('c', 'e'), ('a', 'c'), ('b', 'd')]

关于Python:过滤元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54047517/

相关文章:

python - 如何在多个类中重写而不重复代码 (Python)

MATLAB:IIR 滤波器的实时 vs. filter(b,a,z) 实现

javascript - 如何在 'N/search'模块过滤器中添加带括号的过滤条件

c++ - 如何用相同的参数初始化所有元组元素?

具有可变宽度大小的 Python 峰值检测

python - 如何以编程方式获取属性错误的目标?

python - 我如何使用 python 截断 url

javascript - 当被过滤的数组包含 JSON 数据时,为什么我会收到 'cannot read property ' filter' of undefined' ?

c# - 返回两个值,元组 vs 'out' vs 'struct'

python - 使用 BeautifulSoup 迭代 XML 以提取特定标签并存储在变量中