集合中的 union() 和 union_update() 之间的区别,以及其他? [英] Difference between union() and union_update() in sets, and others?

查看:91
本文介绍了集合中的 union() 和 union_update() 之间的区别,以及其他?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python 集合有这些方法:

s.union(t) s |t 包含 s 和 t 元素的新集合s.update(t) s |= t 返回从 t​​ 添加元素的集合 s

同样,还有这些:

s.intersection_update(t) s &= t return set s 只保留在 t 中也找到的元素s.intersection(t) s &t 具有 s 和 t 共有元素的新集合

依此类推,适用于所有标准关系代数运算.

所以...问题是,这里到底有什么区别?我看到它说 update() 版本返回 s 而不是新集合,但是如果我写 x = s.update(t),这是否意味着 id(x)== id(s)?它们现在是否引用了同一个对象?

我的意思是,我真的不明白为什么要实现这两组方法.它似乎没有添加任何重要的功能.

解决方案

它们非常不同.一个集合就地改变集合,而另一个保持原始集合不变,而是返回一个副本.

<预><代码>>>>s = {1, 2, 3}>>>新闻 = s |{4}>>>秒设置([1, 2, 3])>>>消息设置([1, 2, 3, 4])

注意 s 是如何保持不变的.

<预><代码>>>>s.update({4})>>>秒设置([1, 2, 3, 4])

现在我已经改变了 s 本身.还要注意 .update() 似乎没有返回任何东西;它没有将 s 返回给调用者,Python 解释器也没有回显值.

就地更改对象的方法在 Python 中永远不会返回原始对象.它们的返回值总是 None 而不是(从不回显).

Python sets have these methods:

s.union(t)  s | t   new set with elements from both s and t

s.update(t) s |= t  return set s with elements added from t

Likewise, there's also these:

s.intersection_update(t)    s &= t  return set s keeping only elements also found in t

s.intersection(t)   s & t   new set with elements common to s and t

And so on, for all the standard relational algebra operations.

So...question is, what exactly is the difference here? I see that it says that the update() versions returns s instead of a new set, but if I write x = s.update(t), does that means that id(x) == id(s)? Are they references to the same object now?

I mean, I don't really see why both sets of methods are implemented. It doesn't seem to add any significant functionality.

解决方案

They are very different. One set changes the set in place, while the other leaves the original set alone, and returns a copy instead.

>>> s = {1, 2, 3}
>>> news = s | {4}
>>> s
set([1, 2, 3])
>>> news
set([1, 2, 3, 4])

Note how s has remained unchanged.

>>> s.update({4})
>>> s
set([1, 2, 3, 4])

Now I've changed s itself. Note also that .update() didn't appear to return anything; it did not return s to the caller and the Python interpreter did not echo a value.

Methods that change objects in-place never return the original in Python. Their return value is always None instead (which is never echoed).

这篇关于集合中的 union() 和 union_update() 之间的区别,以及其他?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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