我有两个元组列表。我想要一个新列表,其中包含 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/