Python:以函数式编程方式组合两个列表并删除重复项

Python:以函数式编程方式组合两个列表并删除重复项,python,functional-programming,Python,Functional Programming,我正在尝试编写一个函数,它可以在删除重复项的同时合并两个列表,但使用的是纯函数的方式。 例如: a = [1,2,2] b = [1,3,3,4,5,0] union(a,b) --> [1,2,3,4,5,0] 守则的强制性形式是: def union(a,b): c = [] for i in a + b: if i not in c: c.append(i) return c 我尝试了几种方法,但没有找到一种不使用循

我正在尝试编写一个函数,它可以在删除重复项的同时合并两个列表,但使用的是纯函数的方式。 例如:

a = [1,2,2]
b = [1,3,3,4,5,0]
union(a,b) --> [1,2,3,4,5,0]
守则的强制性形式是:

def union(a,b):
    c = []
    for i in a + b:
        if i not in c:
            c.append(i)
    return c

我尝试了几种方法,但没有找到一种不使用循环检查项目的方法-我缺少什么?

如果您想保持订单,可以使用
集合。OrderedDict
,否则只需使用
设置
。这些数据结构使用其项的散列值来保存它们,因此它们不会保留重复项

In [11]: from collections import OrderedDict

In [12]: list(OrderedDict.fromkeys(a+b))
Out[12]: [1, 2, 3, 4, 5, 0]

要合并这两个列表,请执行以下操作:

a = [1,2,2]
b = [1,3,3,4,5,0]
使用集合:

union = set(a) | set(b)
# -> set([0, 1, 2, 3, 4, 5])
使用理解列表:

union = a + [x for x in b if x not in a]
# -> [1, 2, 2, 3, 3, 4, 5, 0]
使用循环,不重复,保持顺序:

union = []
for x in a + b:
    if x not in union:
        union.append(x)
# -> [1, 2, 3, 4, 5, 0]

您是否尝试过使用
集合

>>> a = [1,2,2]
>>> b = [1,3,3,4,5,0]
>>> list(set(a).union(set(b)))
[0, 1, 2, 3, 4, 5]
怎么样

>>> x = [1,2,3]
>>> y = [1,3,5,7,9]
>>> list(set(x).union(set(y)))

这将组合两个列表
a
b
,使用
set
只取唯一的值,然后我们可以将其返回到
list

如果您不介意导入库,请为此()使用
toolz
,它通常是使用Python进行函数式编程的有用且广泛使用的助手。它有一个名为
unique
()的函数,它完全满足您的需要

from toolz.itertoolz import unique
a = [1,2,2,3,0]
b = [1,3,3,4,5,0]
c = a + b # could do that with itertools.chain() in a more functional way
return list(unique(c))
# -> [1, 2, 3, 0, 4, 5]

集合
没有保留顺序。OP从未要求他要保留顺序?不幸的是,我希望保留顺序,因此这并不能解决我的问题,尽管我很欣赏solution@DanielR:那么你必须在你的问题中提到这一点。我们猜不出你想要什么。
from toolz.itertoolz import unique
a = [1,2,2,3,0]
b = [1,3,3,4,5,0]
c = a + b # could do that with itertools.chain() in a more functional way
return list(unique(c))
# -> [1, 2, 3, 0, 4, 5]