创建包含在多个列表中的所有值的并集的Pythonic方法 [英] Pythonic way to create union of all values contained in multiple lists

查看:192
本文介绍了创建包含在多个列表中的所有值的并集的Pythonic方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表列表:

lists = [[1,4,3,2,4], [4,5]]

我想弄平此列表并删除所有重复项;或者换句话说,应用设置的并集操作:

I want to flatten this list and remove all duplicates; or, in other words, apply a set union operation:

desired_result = [1, 2, 3, 4, 5]

最简单的方法是什么?

What's the easiest way to do this?

推荐答案

set.union 可以满足您的要求:

set.union does what you want:

>>> results_list = [[1,2,3], [1,2,4]]
>>> results_union = set().union(*results_list)
>>> print(results_union)
set([1, 2, 3, 4])

您还可以使用两个以上的列表来完成此操作.

You can also do this with more than two lists.

这篇关于创建包含在多个列表中的所有值的并集的Pythonic方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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