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

标签 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

我尝试了几种方法,但找不到不使用循环遍历项目的方法 - 我错过了什么?

最佳答案

list(set(a + b))

这结合了两个列表 ab 并且使用 set 只接受唯一的值然后我们可以将它返回到 list

关于Python:以函数式编程方式组合两个列表并删除重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39734485/

相关文章:

python - 狮身人面像/rST : using configuration values in include statements?

python - numpy滑动二维窗口计算

javascript - JavaScript 中的范围式迭代器

functional-programming - (Racket) 返回满足条件的列表的子列表

list - 只能使用cons car cdr

Haskell 模块命名约定

python - 从 PyTorch 自定义数据集的 __getitem__ 中的巨大未压缩 tar 文件读取图像的最快方法

python - python中的安全凭证存储

performance - Haskell/GHC 内存了多少?

c# - Python在控制台应用程序中执行外部Python脚本