python中多个集合的并集 [英] Union of multiple sets in python

查看:1002
本文介绍了python中多个集合的并集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

[[1, '34', '44'], [1, '40', '30', '41'], [1, '41', '40', '42'], [1, '42', '41', '43'], [1, '43', '42', '44'], [1, '44', '34', '43']]

我有一个清单清单.我的目的是检查任何一个子列表是否与其他子列表(除了要比较的第一个索引对象)有任何共同点.如果有任何共同点,则统一这些子列表.

I have a list of lists. My aim is to check whether any one sublist has anything in common with other sublists(excluding the first index object to compare). If it has anything in common then unify those sublists.

例如,对于本示例,我的最终答案应为:

For example, for this example my final answer should be something like:

[[1, '34, '44', '40' '30', '41', '42', '43']]

我知道我应该将子列表转换为集合,然后使用union()和交集()操作.但是我坚持的是如何比较每个集合/子列表.我无法对列表进行循环,并逐个比较每个子列表,因为列表的内容将被修改,这会导致错误.

I can understand that I should convert the sublists to sets and then use union() and intersection() operation. But what I am stuck with is to how to compare each set/sublist. I can't run a loop over the list and compare each sublist one by one as the contents of the list would be modified and this would lead to error.

我想知道有什么有效的方法可以比较所有子列表(转换为集合)并进行合并吗?

What I want to know is there any efficient method to compare all the sublists(converted to sets) and get union of them?

推荐答案

itertools 模块可简化此问题的工作:

The itertools module makes short work of this problem:

>>> from itertools import chain
>>> list(set(chain.from_iterable(d)))
[1, '41', '42', '43', '40', '34', '30', '44']

另一种方法是将列表解压缩为 union()的单独参数:

Another way to do it is to unpack the list into separate arguments for union():

>>> list(set().union(*d))
[1, '41', '42', '43', '40', '34', '30', '44']

后一种方法消除了所有重复项,并且不需要先将输入转换为集合.另外,它不需要导入.

The latter way eliminates all duplicates and doesn't require that the inputs first be converted to sets. Also, it doesn't require an import.

这篇关于python中多个集合的并集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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