我无法理解 if 语句条件的语句的评估顺序:
假设我有一本这样的字典,它将单词映射到网页列表:
index = { WORD, [url1,url2,url3] }
插入此索引时有两种情况:
1)索引中已经不存在键(WORD),需要创建一个列表,并将WORD设置为
map中的键
2)键(WORD)已经存在于索引中,我只需要将当前url附加到字典中已经存在的列表中
我期望的工作:
def update_index(word, url):
if word in index and not(url in index[word]):
index[word].append(url) # list already exists append to it
else:
index[word] = [url] # new list with url as a single element
然而,这仅允许每个单词 1 个 url。
什么工作:
def update_index(word, url):
if word in index: # <- isnt having two consecutive if statements
# the same as an AND???
if not(url in index[word]):
index[word].append(url) # list already exists append to it
else:
index[word] = [url] # new list with url as a single element
任何帮助解决这个问题将不胜感激。