python错误'dict'对象没有属性:'add'

stt*_*stt 1 python dictionary add

我编写此代码作为字符串列表中的简单搜索引擎,如下例所示:

mii(['hello world','hello','hello cat','hellolot of cats']) == {'hello': {0, 1, 2}, 'cat': {2}, 'of': {3}, 'world': {0}, 'cats': {3}, 'hellolot': {3}}
Run Code Online (Sandbox Code Playgroud)

但我不断得到错误

'dict' object has no attribute 'add'
Run Code Online (Sandbox Code Playgroud)

我该怎么解决?

def mii(strlist):
    word={}
    index={}
    for str in strlist:
        for str2 in str.split():
            if str2 in word==False:
                word.add(str2)
                i={}
                for (n,m) in list(enumerate(strlist)):
                    k=m.split()
                    if str2 in k:
                        i.add(n)
                index.add(i)
    return { x:y for (x,y) in zip(word,index)}
Run Code Online (Sandbox Code Playgroud)

sir*_*rfz 9

在Python中,当您word = {}在创建dict对象而不是set对象(我假设是您想要的对象)时初始化对象.要创建一个集合,请使用:

word = set()
Run Code Online (Sandbox Code Playgroud)

您可能对Python的Set Comprehension感到困惑,例如:

myset = {e for e in [1, 2, 3, 1]}
Run Code Online (Sandbox Code Playgroud)

这导致set包含元素1,2和3.类似Dict理解:

mydict = {k: v for k, v in [(1, 2)]}
Run Code Online (Sandbox Code Playgroud)

导致带有键值对的字典1: 2.


Dra*_*ord 7

x = [1, 2, 3] # is a literal that creates a list (mutable array).  
x = []  # creates an empty list.

x = (1, 2, 3) # is a literal that creates a tuple (constant list).  
x = ()  # creates an empty tuple.

x = {1, 2, 3} # is a literal that creates a set.  
x = {}  # confusingly creates an empty dictionary (hash array), NOT a set, because dictionaries were there first in python.  
Run Code Online (Sandbox Code Playgroud)

使用

x = set() # to create an empty set.
Run Code Online (Sandbox Code Playgroud)

另请注意

x = {"first": 1, "unordered": 2, "hash": 3} # is a literal that creates a dictionary, just to mix things up. 
Run Code Online (Sandbox Code Playgroud)