2017-09-03 7 views
0

なぜ、2番目の印刷参照メソッドが空白を返し、リンクacm.orgを返しませんか?最初の結果は理にかなっていますが、2番目の結果は似ていませんか?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

字下げが誤っています。 最初ののエントリが一致しない場合は、[]を返します。それは次のとおりです:

+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を使った柔軟な作業の可能性があります。

関連する問題