如何将项目添加到python中的空集
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17511270/
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
How can I add items to an empty set in python
提问by user2192774
I have the following procedure:
我有以下程序:
def myProc(invIndex, keyWord):
D={}
for i in range(len(keyWord)):
if keyWord[i] in invIndex.keys():
D.update(invIndex[query[i]])
return D
But I am getting the following error:
但我收到以下错误:
Traceback (most recent call last):
File "<stdin>", line 3, in <module>
TypeError: cannot convert dictionary update sequence element #0 to a sequence
I do not get any error if D contains elements. But I need D to be empty at the beginning.
如果 D 包含元素,我不会收到任何错误。但我需要 D 一开始是空的。
采纳答案by Ashwini Chaudhary
D = {}
is a dictionary not set.
D = {}
是未设置的字典。
>>> d = {}
>>> type(d)
<type 'dict'>
Use D = set()
:
使用 D = set()
:
>>> d = set()
>>> type(d)
<type 'set'>
>>> d.update({1})
>>> d.add(2)
>>> d.update([3,3,3])
>>> d
set([1, 2, 3])
回答by Sukrit Kalra
>>> d = {}
>>> D = set()
>>> type(d)
<type 'dict'>
>>> type(D)
<type 'set'>
What you've made is a dictionary and not a Set.
你所做的是一本字典而不是一个集合。
The update
method in dictionary is used to update the new dictionary from a previous one, like so,
update
字典中的方法用于从以前的字典更新新字典,如下所示,
>>> abc = {1: 2}
>>> d.update(abc)
>>> d
{1: 2}
Whereas in sets, it is used to add elements to the set.
而在集合中,它用于向集合添加元素。
>>> D.update([1, 2])
>>> D
set([1, 2])
回答by lincoln ajanga
When you assign a variable to empty curly braces {} eg: new_set = {}
, it becomes a dictionary.
To create an empty set, assign the variable to a 'set()' ie: new_set = set()
当您将变量分配给空花括号 {} eg: 时new_set = {}
,它就变成了字典。要创建一个空集,请将变量分配给“set()”,即:new_set = set()