Python的Set Union和Set Intersection操作不同吗? [英] Python set Union and set Intersection operate differently?

查看:171
本文介绍了Python的Set Union和Set Intersection操作不同吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Python中进行一些设置操作,我发现有些奇怪.

I'm doing some set operations in Python, and I noticed something odd..

>> set([1,2,3]) | set([2,3,4])
set([1, 2, 3, 4])
>> set().union(*[[1,2,3], [2,3,4]])
set([1, 2, 3, 4])

这是预期的好行为-但有交叉点:

That's good, expected behaviour - but with intersection:

>> set([1,2,3]) & set([2,3,4])
set([2, 3])
>> set().intersection(*[[1,2,3], [2,3,4]])
set([])

我在这里迷失了方向吗?为什么set.intersection()不能按我期望的那样运行?

Am I losing my mind here? Why isn't set.intersection() operating as I'd expect it to?

我如何像联合处理那样做多个集合的交集(假设[[1,2,3], [2,3,4]]有更多的列表)? "pythonic"方式是什么?

How can I do the intersection of many sets as I did with union (assuming the [[1,2,3], [2,3,4]] had a whole bunch more lists)? What would the "pythonic" way be?

推荐答案

执行set()时,您正在创建一个空集.当您执行set().intersection(...)时,您正在将此空集与其他内容相交.空集与任何其他集合的交集为空.

When you do set() you are creating an empty set. When you do set().intersection(...) you are intersecting this empty set with other stuff. The intersection of an empty set with any other collection of sets is empty.

如果实际上有一个 sets 的列表,则可以得到它们的交集,就像您做的那样.

If you actually have a list of sets, you can get their intersection similar to how you did it.

>>> x = [{1, 2, 3}, {2, 3, 4}, {3, 4, 5}]
>>> set.intersection(*x)
set([3])

但是,您不能直接使用它的方式执行此操作,因为在您使用intersection(*...)的示例中实际上根本没有任何集合.您只有一个列表列表.您应该首先将列表中的元素转换为集合.所以如果你有

You can't do this directly with the way you're doing it, though, because you don't actually have any sets at all in your example with intersection(*...). You just have a list of lists. You should first convert the elements in your list to sets. So if you have

x = [[1,2,3], [2,3,4]]

你应该做

x = [set(a) for a in x]

这篇关于Python的Set Union和Set Intersection操作不同吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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