创建多个列表中包含的所有值的并集的 Pythonic 方法
我有一个列表列表:
lists = [[1,4,3,2,4], [4,5]]
我想展平这个列表并删除所有重复项;或者,换句话说,应用集合并运算:
desired_result = [1, 2, 3, 4, 5]
执行此操作的最简单方法是什么?
I have a list of lists:
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
set.union
执行您的操作想要:您也可以使用两个以上的列表来执行此操作。
set.union
does what you want:You can also do this with more than two lists.
由于您似乎使用的是 Python 2.5(如果您需要版本 != 2.6 的 A,顺便说一句,当前的生产版本,那么在 Q 中会很好提及;-)并且想要一个列表而不是结果集,我建议:
itertools 通常是使用迭代器(以及许多类型的序列或集合)的好方法,我衷心建议您熟悉它。
itertools.chain
特别记录在 这里。Since you seem to be using Python 2.5 (it would be nice to mention in your Q if you need an A for versions != 2.6, the current production one, by the way;-) and want a list rather than a set as the result, I recommend:
itertools is generally a great way to work with iterators (and so with many kinds of sequences or collections) and I heartily recommend you become familiar with it.
itertools.chain
, in particular, is documented here.你也可以效仿这个风格
You can also follow this style
以理解方式:
或
in comprehension way:
or
并集不受列表支持,列表是有序的,但集支持。查看 set.union。
Unions are not supported by lists, which are ordered, but are supported by sets. Check out set.union.
我使用以下方法进行相交,这避免了对集合的需要。
或者,
I used the following to do intersections, which avoids the need for sets.
or,