[英]Python “Error 'dict' object has no attribute 'load'”
[英]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 的 Set Comprehension 感到困惑,例如:
myset = {e for e in [1, 2, 3, 1]}
这导致包含元素 1、2 和 3 的set
。类似地,Dict Comprehension:
mydict = {k: v for k, v in [(1, 2)]}
结果是一个键值对为1: 2
的字典。
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.
利用
x = set() # to create an empty set.
另请注意
x = {"first": 1, "unordered": 2, "hash": 3} # is a literal that creates a dictionary, just to mix things up.
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]}
我想这就是你想要的。
我在您的功能中发现了很多问题-
在 Python 中{}
是一个空字典,而不是 set ,要创建一个集合,您应该使用内置函数set()
。
if 条件 - if str2 in word==False:
,由于运算符链接,永远不会达到 True ,它将被转换为 - if str2 in word and word==False
,显示此行为的示例 -
>>> 'a' in 'abcd'==False False >>> 'a' in 'abcd'==True False
在线 - for (n,m) in list(enumerate(strlist))
- 您不需要将enumerate()
函数的返回转换为列表,您只需迭代其返回值(直接是迭代器)
集合没有任何顺序感,当您这样做时 - zip(word,index)
- 无法保证元素以您想要的正确顺序压缩(因为它们根本没有任何顺序感)。
不要使用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}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.