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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31656572/
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 10:21:38  来源:igfitidea点击:

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

pythondictionaryadd

提问by stt

I wrote this code to perform as a simple search engine in a list of strings like the example below:

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

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

but I constantly get the error

但我不断收到错误

'dict' object has no attribute 'add'

how can I fix it?

我该如何解决?

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

采纳答案by sirfz

In Python, when you initialize an object as word = {}you're creating a dictobject and not a setobject (which I assume is what you wanted). In order to create a set, use:

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

word = set()

You might have been confused by Python's Set Comprehension, e.g.:

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

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

which results in a setcontaining elements 1, 2 and 3. Similarly Dict Comprehension:

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

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

results in a dictionary with key-value pair 1: 2.

结果是一个带有键值对的字典1: 2

回答by Morishiri

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

Output:

输出:

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

I think this is what you wanted.

我想这就是你想要的。

回答by Anand S Kumar

I see lots of issues in your function -

我看到你的函数有很多问题 -

  1. In Python {}is an empty dictionary, not a set , to create a set, you should use the builtin function set().

  2. The if condition - if str2 in word==False:, would never amount to True because of operator chaining, it would be converted to - if str2 in word and word==False, example showing this behavior -

    >>> 'a' in 'abcd'==False
    False
    >>> 'a' in 'abcd'==True
    False
    
  3. In line - for (n,m) in list(enumerate(strlist))- You do not need to convert the return of enumerate()function to list, you can just iterate over its return value (which is an iterator directly)

  4. Sets do not have any sense of order, when you do - zip(word,index)- there is no guarantee that the elements are zipped in the correct order you want (since they do not have any sense of order at all).

  5. Do not use stras a variable name.

  1. 在 Python 中{}是一个空字典,而不是一个 set ,要创建一个 set ,你应该使用内置函数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()函数的返回转换为列表,你可以迭代它的返回值(直接是一个迭代器)

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

  5. 不要str用作变量名。

Given this, you are better off directly creating the dictionary from the start , rather than sets.

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

Code -

代码 -

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

Demo -

演示 -

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