笔记:udacity计算机科学导论- 课程15/1-3 初步建立关键字、url对应表

前面课程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()函数,因此无法向搜索字符串一样确定某个关键字的位置 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值