Python:以功能性编程方式合并两个列表并删除重复项 [英] Python: Combining two lists and removing duplicates in a functional programming way

查看:235
本文介绍了Python:以功能性编程方式合并两个列表并删除重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个函数,该函数将两个列表组合在一起,同时删除重复项,但以一种纯粹的功能方式进行. 例如:

I'm trying to write a function that would combine two lists while removing duplicate items, but in a pure functional way. For example:

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

我尝试了几种方法,但是找不到一种方法而又不使用循环遍历项目-我想念的是什么?

I've tried several approaches, but couldn't find a way to do that without using a loop to go over the items - what am I missing?

推荐答案

list(set(a + b))

这结合了两个列表ab,并且使用set仅采用唯一的值,然后我们可以将其返回到list.

This combines two lists a and b and using set takes only unique vales and then we can make it back to list.

这篇关于Python:以功能性编程方式合并两个列表并删除重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆