我写了这段代码,作为一个简单的搜索引擎在一个字符串列表中执行,就像下面的例子。
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]}
的结果是 set
包含元素1、2、3。同样Dict Comprehension。
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]}
我想这是你想要的
我在你的函数中看到很多问题
在Python中 {}
是一个空字典,而不是一个集合,要创建一个集合,你应该使用内置的函数 set()
.
如果条件是: 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()
函数到list,你可以直接在它的返回值上迭代(直接是一个迭代器)。
集没有任何秩序感,当你有------。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}}
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}是一个创建字典的文字,只是为了混淆视听。