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

python error 'dict' object has no attribute: 'add'

我编写这段代码是为了在字符串列表中执行一个简单的搜索引擎,如下例所示:

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

但我经常收到错误

'dict' object has no attribute 'add'

我该如何解决?

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

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

word = set()

您可能对Python的集合理解感到困惑,例如:

myset = {e for e in [1, 2, 3, 1]}

这导致 set 包含元素 1、2 和 3。类似地字典理解:

mydict = {k: v for k, v in [(1, 2)]}

生成具有键值对 1: 2 的字典。

def mii(strlist):
    word_list = {}
    for index, str in enumerate(strlist):
        for word in str.split():
            if word not in word_list.keys():
                word_list[word] = [index]
            else:
                word_list[word].append(index)
    return word_list

print mii(['hello world','hello','hello cat','hellolot of cats'])

输出:

{'of': [3], 'cat': [2], 'cats': [3], 'hellolot': [3], 'world': [0], 'hello': [0, 1, 2]}

我想这就是你想要的。

我发现你的函数有很多问题 -

  1. 在Python中 {}是一个空字典,不是集合,要创建一个集合,你应该使用内置函数set() .

  2. if 条件 - if str2 in word==False: 永远不会因为运算符链接而达到 True,它将被转换为 - if str2 in word and word==False ,显示此行为的示例 -

    >>> 'a' in 'abcd'==False
    False
    >>> 'a' in 'abcd'==True
    False
    
  3. 行 - for (n,m) in list(enumerate(strlist)) - 您不需要将 enumerate() 函数的 return 转换为列表,您可以迭代其 return value(直接就是一个迭代器)

  4. 集没有任何顺序感,当你这样做时 - zip(word,index) - 不能保证元素以你想要的正确顺序压缩(因为它们没有任何秩序感)。

  5. 不要使用 str 作为变量名。

鉴于此,您最好从一开始就直接创建字典,而不是集合。

代码-

def mii(strlist):
    word={}
    for i, s in enumerate(strlist):
        for s2 in s.split():
            word.setdefault(s2,set()).add(i)
    return word

演示 -

>>> def mii(strlist):
...     word={}
...     for i, s in enumerate(strlist):
...         for s2 in s.split():
...             word.setdefault(s2,set()).add(i)
...     return word
...
>>> mii(['hello world','hello','hello cat','hellolot of cats'])
{'cats': {3}, 'world': {0}, 'cat': {2}, 'hello': {0, 1, 2}, 'hellolot': {3}, 'of': {3}}

x = [1, 2, 3] 是创建列表(可变数组)的文字。
x = [] 创建一个空列表。

x = (1, 2, 3) 是创建元组(常量列表)的文字。
x = () 创建一个空元组。

x = {1, 2, 3} 是一个创建集合的文字。
x = {} 混淆地创建了一个空字典(哈希数组),而不是一个集合,因为字典首先出现在 python 中。

使用
x = set() 创建一个空集。

另请注意
x = {"first": 1, "unordered": 2, "hash": 3} 是创建字典的文字,只是为了混淆。