2017-09-03 7 views
0

Warum gibt die zweite Druck-Lookup-Methode ein Leerzeichen zurück und nicht den Link acm.org? Das erste Ergebnis ist sinnvoll, aber sollte das zweite Ergebnis nicht ähnlich sein?Probleme beim Verständnis der Python-Ausgabe

# 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'] 
[] 

Antwort

0

Ihr Einzug hat einen Tippfehler. Sie geben [] zurück, wenn der erste Eintrag nicht übereinstimmt. Es sollte sein:

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

danke..ich bin so ein Noob. Werde beim nächsten Mal vorsichtiger sein. – algorythms

0

Ich empfehle dringend Wörterbücher für diesen Fall.

Es wird so sein:

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

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

Dies ist schneller und deutlich. Und sicher haben Sie mehr Möglichkeiten für flexibles Arbeiten mit dict als mit [Liste von [Listen von 'Strings' und [Liste von 'Strings']]]].

Verwandte Themen