在python的集合操作中添加vs更新 [英] add vs update in set operations in python
问题描述
如果我只想向集合中添加单个值,python 中的添加和更新操作有什么区别.
a = set()a.update([1]) #worksa.add(1) #worksa.update([1,2])#worksa.add([1,2])#失败
谁能解释一下为什么会这样.
set.add
将单个元素添加到集合中.所以,
工作,但它不能与可迭代一起工作,除非它是可散列的.这就是 a.add([1, 2])
失败的原因.
此处,[1, 2]
被视为添加到集合中的元素,如错误消息所述,一个列表不能被散列,但一个集合的所有元素都应该是可散列的.引用文档、
返回一个新的 set
或 frozenset
对象,其元素取自可迭代对象.集合的元素必须hashable.
如果 set.update
,您可以将多个可迭代对象传递给它,它将迭代所有可迭代对象,并将包含集合中的各个元素.记住:它只能接受可迭代对象.这就是为什么当您尝试使用 1
但是,下面的方法会起作用,因为列表 [1]
被迭代并且列表的元素被添加到集合中.
set.update
基本上相当于就地集合联合操作.考虑以下情况
在这里,我们显式地将所有可迭代对象转换为集合,然后我们找到并集.有多个中间集和联合.在这种情况下,set.update
作为一个很好的辅助函数.由于它接受任何迭代,你可以简单地做
What is the difference between add and update operations in python if i just want to add a single value to the set.
a = set()
a.update([1]) #works
a.add(1) #works
a.update([1,2])#works
a.add([1,2])#fails
Can someone explain why is this so.
set.add
adds an individual element to the set. So,
>>> a = set()
>>> a.add(1)
>>> a
set([1])
works, but it cannot work with an iterable, unless it is hashable. That is the reason why a.add([1, 2])
fails.
>>> a.add([1, 2])
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: unhashable type: 'list'
Here, [1, 2]
is treated as the element being added to the set and as the error message says, a list cannot be hashed but all the elements of a set are expected to be hashables. Quoting the documentation,
Return a new
set
orfrozenset
object whose elements are taken from iterable. The elements of a set must be hashable.
In case of set.update
, you can pass multiple iterables to it and it will iterate all iterables and will include the individual elements in the set. Remember: It can accept only iterables. That is why you are getting an error when you try to update it with 1
>>> a.update(1)
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: 'int' object is not iterable
But, the following would work because the list [1]
is iterated and the elements of the list are added to the set.
>>> a.update([1])
>>> a
set([1])
set.update
is basically an equivalent of in-place set union operation. Consider the following cases
>>> set([1, 2]) | set([3, 4]) | set([1, 3])
set([1, 2, 3, 4])
>>> set([1, 2]) | set(range(3, 5)) | set(i for i in range(1, 5) if i % 2 == 1)
set([1, 2, 3, 4])
Here, we explicitly convert all the iterables to sets and then we find the union. There are multiple intermediate sets and unions. In this case, set.update
serves as a good helper function. Since it accepts any iterable, you can simply do
>>> a.update([1, 2], range(3, 5), (i for i in range(1, 5) if i % 2 == 1))
>>> a
set([1, 2, 3, 4])
这篇关于在python的集合操作中添加vs更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!