![](/img/trans.png)
[英]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.