2017-09-03 103 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']]]。