python错误"dict"对象没有属性:"add" [英] python error 'dict' object has no attribute: 'add'

查看:358
本文介绍了python错误"dict"对象没有属性:"add"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

但我经常收到错误消息

'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对象(我认为是你想要什么).为了创建一个集合,使用:

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

word = set()

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

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

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

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

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

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

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

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

这篇关于python错误"dict"对象没有属性:"add"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆