2017-09-03 104 views
0

为什么第二个打印查找方法返回空白而不是链接acm.org?第一个结果是有道理的,但不应该第二个结果是相似的?无法理解python输出

# Define a procedure, lookup, 
# that takes two inputs: 

# - an index 
# - keyword 

# The procedure should return a list 
# of the urls associated 
# with the keyword. If the keyword 
# is not in the index, the procedure 
# should return an empty list. 


index = [['udacity', ['http://udacity.com', 'http://npr.org']], 
     ['computing', ['http://acm.org']]] 

def lookup(index,keyword): 
    for p in index: 
     if p[0] == keyword: 
      return p[1] 
     return []  



print lookup(index,'udacity') 
#>>> ['http://udacity.com','http://npr.org'] 

print lookup(index,'computing') 

Results: 

['http://udacity.com', 'http://npr.org'] 
[] 

回答

0

您的缩进有一个错字。如果第一个条目不匹配,则返回[]。它应该是:

def lookup(index,keyword): 
    for p in index: 
     if p[0] == keyword: 
      return p[1] 
    return [] 
+0

谢谢你..我是一个小菜鸟。下次会更加小心。 – algorythms

0

我强烈建议在这种情况下使用字典。

这将是这样的:

index = {'udacity': ['http://udacity.com', 'http://npr.org'], 
     'computing': ['http://acm.org']} 

def lookup(index, keyword): 
    return index[keyword] if keyword in index else [] 

这是更快,清晰。当然,与dict相比,您有更多灵活工作的可能性,而[list of'strings'和[list of'strings']]]。