问题:如何在python中将项目添加到空集

我有以下步骤:

def myProc(invIndex, keyWord):
    D={}
    for i in range(len(keyWord)):
        if keyWord[i] in invIndex.keys():
                    D.update(invIndex[query[i]])
    return D

但是我收到以下错误:

Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
TypeError: cannot convert dictionary update sequence element #0 to a sequence

如果D包含元素,则不会出现任何错误。但是我需要D在开始时为空。

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.


回答 0

D = {} 是未设置的字典。

>>> d = {}
>>> type(d)
<type 'dict'>

用途 D = set()

>>> d = set()
>>> type(d)
<type 'set'>
>>> d.update({1})
>>> d.add(2)
>>> d.update([3,3,3])
>>> d
set([1, 2, 3])

D = {} is a dictionary not set.

>>> d = {}
>>> type(d)
<type 'dict'>

Use D = set():

>>> d = set()
>>> type(d)
<type 'set'>
>>> d.update({1})
>>> d.add(2)
>>> d.update([3,3,3])
>>> d
set([1, 2, 3])

回答 1

>>> d = {}
>>> D = set()
>>> type(d)
<type 'dict'>
>>> type(D)
<type 'set'>

您制作的是字典而不是Set。

update字典中的方法用于从上一个字典更新新字典,就像这样,

>>> abc = {1: 2}
>>> d.update(abc)
>>> d
{1: 2}

而在集合中,它用于向集合中添加元素。

>>> D.update([1, 2])
>>> D
set([1, 2])
>>> 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,

>>> 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])

回答 2

当您将变量分配给空括号{}例如:时new_set = {},它将成为字典。要创建一个空集,请将变量分配给“ set()”,即:new_set = set()

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()


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。