Python:set.difference和set.difference_update有什么区别? [英] Python: What's the difference between set.difference and set.difference_update?
问题描述
s.difference(t)返回一个新集合,其中 t 中没有任何元素.
s.difference(t) returns a new set with no elements in t.
s.difference_update(t)返回 t 中没有元素的更新集.
s.difference_update(t) returns an updated set with no elements in t.
这两种设置方法有什么区别?由于difference_update更新设置为s,应采取什么预防措施以避免从该方法接收到None的结果?
What's the difference between these two set methods? Because the difference_update updates set s, what precautions should be taken to avoid receiving a result of None from this method?
就速度而言,set.difference_update不应更快,因为您只是从set移除元素,而不是像set.difference()那样创建新的set?
In terms of speed, shouldn't set.difference_update be faster since you're only removing elements from set s instead of creating a new set like in set.difference()?
推荐答案
问.这两种设置方法有什么区别?
Q. What's the difference between these two set methods?
A.. update 版本从现有集中减去,对其进行变异,并有可能使它比原来的更小. non-update 版本会产生一个新的集合,而原始版本则保持不变.
A. The update version subtracts from an existing set, mutating it, and potentially leaving it smaller than it originally was. The non-update version produces a new set, leaving the originals unchanged.
问.由于difference_update更新设置为s,应采取哪些预防措施以避免从该方法接收到None的结果?
Q. Because the difference_update updates set s, what precautions should be taken to avoid receiving a result of None from this method?
A..Python中的变异方法通常返回 None 作为表示它们已变异对象的一种方式.唯一的预防措施"是不将 None 结果分配给变量.
A. Mutating methods in Python generally return None as a way to indicate that they have mutated an object. The only "precaution" is to not assign the None result to a variable.
问.就速度而言,不应该set.difference_update更快,因为您只是从set s中删除元素,而不是像set.difference()那样创建新的set?
Q. In terms of speed, shouldn't set.difference_update be faster since you're only removing elements from set s instead of creating a new set like in set.difference()?
A.是. update 版本的算法只是丢弃值.
A. Yes, the algorithm of the update version simply discards values.
相比之下,非更新版本的算法取决于集合的大小.
In contrast, the algorithm for the non-updating version depends on the size of the sets.
如果 s 的大小是 t 的四倍或更多倍,则新集版本将首先复制主集,然后从中丢弃值.因此"s-t
被实现为 n = s.copy(); n.difference_update(t)
).该算法用于 s 比 t
If the size of s is four or more times larger that t, the new set version first copies the main set and then discards values from it. So "s - t
is implemented as n = s.copy(); n.difference_update(t)
). That algorithm is used when s is much larger than t
否则,非更新版本的算法是创建一个空的新集合 n ,循环遍历 s 的元素并将其添加到 n(如果它们不在 t 中).
Otherwise, the algorithm for the non-updating version is to create an empty new set n, loop over the elements of s and add them to n if they are not present in t.
这篇关于Python:set.difference和set.difference_update有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!