我正在开发一个过程add_to_index,它需要3个输入:
如果关键字已经在索引中,则将url添加到与该关键字关联的url列表中。
如果关键字不在索引中,则索引中将包含一个新元素:
[keyword,[url]]
码
index = []
def add_to_index(index,keyword,url):
flag = 0
count = 0
for lists in index:
count += 1
if(lists[0]==keyword):
index[count][1].append(url)
if(flag ==0):
index.append([keyword,url])
#calling the function below
add_to_index(index,'google','http://google.com')
print index
输出-> [['google', 'http://google.com']]
add_to_index(index,'computing','http://acm.org')
print index
输出-> [['google', 'http://google.com'], ['computing', 'http://acm.org']]
add_to_index(index,'google','http://gmail.com')
print index
错误->
index[count][1].append(url)
AttributeError: 'str' object has no attribute 'append'
预期产量:
[['google', ['http://google.com', 'http://gmail.com']],
['computing', ['http://acm.org']]]
您犯了三个错误,首先,您没有使用flag
和,然后将url作为字符串添加。最后,正如Kaivosuketaja在评论中提到的那样,计数应最后增加。可以通过其他方式完成
index = []
def add_to_index(index,keyword,url):
flag = 0
count = 0
for lists in index:
if(lists[0]==keyword):
flag = 1
index[count][1].append(url)
count += 1
if(flag ==0):
index.append([keyword,[url]])
# Take note of append away here
#calling the function below
add_to_index(index,'google','http://google.com')
print index
add_to_index(index,'computing','http://acm.org')
print index
add_to_index(index,'google','http://gmail.com')
print index
现在的输出是
[['google', ['http://google.com']]]
[['google', ['http://google.com']], ['computing', ['http://acm.org']]]
[['google', ['http://google.com', 'http://gmail.com']], ['computing', ['http://acm.org']]]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句