在python的集合操作中添加vs更新

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28845284/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 03:49:33  来源:igfitidea点击:

add vs update in set operations in python

pythonset

提问by aceminer

What is the difference between add and update operations in python if i just want to add a single value to the set.

如果我只想向集合中添加一个值,python 中的添加和更新操作有什么区别。

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.

有人可以解释为什么会这样。

采纳答案by thefourtheye

set.add

set.add

set.addadds an individual element to the set. So,

set.add将单个元素添加到集合中。所以,

>>> 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])失败的原因。

>>> 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 hashedbut all the elements of a set are expected to be hashables. Quoting the documentation,

在这里,[1, 2]被视为添加到集合中的元素,正如错误消息所说,列表不能被散列,但集合的所有元素都应该是可散列的。引用文档

Return a new setor frozensetobject whose elements are taken from iterable. The elements of a set must be hashable.

返回一个新的setfrozenset对象,其元素取自可迭代对象。集合的元素必须是可散列的

set.update

set.update

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

在 的情况下set.update,您可以将多个可迭代对象传递给它,它将迭代所有可迭代对象并将包含集合中的各个元素。请记住:它只能接受可迭代对象。这就是为什么当您尝试使用以下内容更新时会收到错误的原因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.

但是,由于列表[1]被迭代并且列表的元素被添加到集合中,所以下面的方法会起作用。

>>> a.update([1])
>>> a
set([1])

set.updateis basically an equivalent of in-place set union operation. Consider the following cases

set.update基本上相当于就地设置联合操作。考虑以下情况

>>> 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.updateserves as a good helper function. Since it accepts any iterable, you can simply do

在这里,我们显式地将所有可迭代对象转换为集合,然后我们找到并集。有多个中间集和联合。在这种情况下,set.update作为一个很好的辅助函数。由于它接受任何迭代,你可以简单地做

>>> a.update([1, 2], range(3, 5), (i for i in range(1, 5) if i % 2 == 1))
>>> a
set([1, 2, 3, 4])

回答by Padraic Cunningham

addis faster for a single element because it is exactly for that purpose, adding a single element:

add对于单个元素更快,因为它正是为此目的,添加单个元素:

In [5]: timeit a.update([1])
10000000 loops, best of 3: 191 ns per loop

In [6]: timeit a.add(1) 
10000000 loops, best of 3: 69.9 ns per loop

updateexpects an iterable or iterables so if you have a single hashable element to add then use addif you have an iterable or iterables of hashable elements to add use update.

update期望一个 iterable 或 iterables 所以如果你有一个单独的 hashable 元素要添加然后使用addif 你有一个 iterable 或 iterables 的 hashable 元素要添加 use update

s.add(x) add element x to set s

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

s.add(x) 添加元素 x 到集合 s

s.update(t) s |= t 返回从 t​​ 添加元素的集合 s

回答by Akavall

addadds an element, update"adds" another iterable set, listor tuple, for example:

add添加一个元素,update“添加”另一个可迭代对象setlist或者tuple,例如:

In [2]: my_set = {1,2,3}

In [3]: my_set.add(5)

In [4]: my_set
Out[4]: set([1, 2, 3, 5])

In [5]: my_set.update({6,7})

In [6]: my_set
Out[6]: set([1, 2, 3, 5, 6, 7])

回答by monkut

.add()is intended for a single element, while .update()is for the introduction of other sets.

.add()用于单个element,而.update()用于引入其他集合。

From help():

从帮助():

add(...)
    Add an element to a set.

    This has no effect if the element is already present.


update(...)
    Update a set with the union of itself and others.

回答by Frank

addonly accepts a hashable type. A list is not hashable.

add只接受可散列的类型。列表不可散列。

回答by ekipmanager

a.update(1)in your code won't work. addaccepts an element and put it in the set if it is not already there but updatetakes an iterable and makes a unions of the set with that iterable. It's kind of like appendand extendfor the lists.

a.update(1)在您的代码中不起作用。add接受一个元素并将其放入集合中(如果它不存在),但update需要一个可迭代对象,并将该集合与该可迭代对象合并。这有点像append,并extend为列表。

回答by harrisonthu

I guess no one mentioned about the good resource from Hackerrank. I'd like to paste how Hackerrank mentions the difference between update and add for set in python.

我想没有人提到 Hackerrank 的好资源。我想粘贴 Hackerrank 如何提到在 python 中更新和添加集之间的区别。

Sets are unordered bag of unique values. A single set contains values of any immutable data type.

集合是唯一值的无序包。单个集合包含任何不可变数据类型的值。

CREATING SET

创作集

myset = {1, 2} # Directly assigning values to a set

myset = set() # Initializing a set

myset = set(['a', 'b']) # Creating a set from a list

print(myset)  ===> {'a', 'b'}

MODIFYING SET - add() and update()

修改集 - add() 和 update()

myset.add('c')

myset  ===>{'a', 'c', 'b'}

myset.add('a') # As 'a' already exists in the set, nothing happens

myset.add((5, 4))

print(myset) ===> {'a', 'c', 'b', (5, 4)} 


myset.update([1, 2, 3, 4]) # update() only works for iterable objects

print(myset) ===> {'a', 1, 'c', 'b', 4, 2, (5, 4), 3}

myset.update({1, 7, 8})

print(myset) ===>{'a', 1, 'c', 'b', 4, 7, 8, 2, (5, 4), 3}

myset.update({1, 6}, [5, 13])

print(myset) ===> {'a', 1, 'c', 'b', 4, 5, 6, 7, 8, 2, (5, 4), 13, 3}

Hope it helps. For more details on Hackerrank, here is the link.

希望能帮助到你。有关 Hackerrank 的更多详细信息,请访问这里的链接。

回答by PRATIK M VYAS

add method directly adds elements to the set while the update method converts first argument into set then it adds the list is hashable therefore we cannot add a hashable list to unhashable set.

add 方法直接将元素添加到集合中,而 update 方法将第一个参数转换为集合,然后将列表添加为可散列的,因此我们不能将可散列的列表添加到不可散列的集合中。

回答by Rudra

We use add()method to add single value to a set.

我们使用add()方法将单个值添加到集合中。

We use update()method to add sequence values to a set.

我们使用update()方法将序列值添加到集合中。

Here Sequences are any iterables including list,tuple,string,dictetc.

这里序列是任何iterables包括listtuplestringdict等。