前面课程2,讲述了当前最被认可的关键字、url对应表数据结构, [keyword1,[url11, url12,....],keyword2,[url21, url22,....]]
即以搜索的关键字为基础,索引同一个关键字的所有对应url,这样可以减少搜索url的数量
# Define a procedure, add_to_index,
# that takes 3 inputs:# - an index: [[<keyword>,[<url>,...]],...]
# - a keyword: String
# - a url: String
# If the keyword is already
# in the index, add the url
# to the list of urls associated
# with that keyword.
# If the keyword is not in the index,
# add an entry to the index: [keyword,[url]]
index = []
a = 0
def add_to_index(index,keyword,url):
for i in index:
if i[0] == keyword:
i[1].append(url)
return
index.append([keyword,[url]])
add_to_index(index,'udacity','http://udacity.com')
add_to_index(index,'computing','http://acm.org')
add_to_index(index,'udacity','http://npr.org')
print index
#add_to_index(index,'udacity','http://udacity.com')
#add_to_index(index,'computing','http://acm.org')
#add_to_index(index,'udacity','http://npr.org')
#print index
#>>> [['udacity', ['http://udacity.com', 'http://npr.org']],
#>>> ['computing', ['http://acm.org']]]
这题的关键点在于,keyword和对应的url作为index列表的一个子元素存在,这种设计让i[0]、i[1]可以遍历索引库中的关键字和url。
另外一个难点是,在for循环后,要加return,否则结果会变成:
[['udacity', ['http://udacity.com', 'http://npr.org']],
#>>> ['computing', ['http://acm.org']],['udacity','http://npr.org']]]
注意: list中没有find()函数,因此无法向搜索字符串一样确定某个关键字的位置