[英]Having trouble understanding python output
为什么第二种打印查找方法返回空白而不是链接acm.org? 第一个结果有意义,但是第二个结果不应该相似吗?
# 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']
[]
您的缩进有错字。 如果第一个条目不匹配,您将返回[]
。 它应该是:
def lookup(index,keyword):
for p in index:
if p[0] == keyword:
return p[1]
return []
我强烈建议在这种情况下使用字典。
就像这样:
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灵活工作的可能性更大。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.