python向后移植某些方法
问题内容:
以下方法与python 2.4配合使用是否有任何反向移植:
any, all, collections.defaultdict, collections.deque
问题答案:
好吧,至少对于any
而且all
很容易:
def any(iterable):
for element in iterable:
if element:
return True
return False
def all(iterable):
for element in iterable:
if not element:
return False
return True
deque
已经在2.4中了。
至于defaultdict
,我想您可以轻松地模仿它setdefault()
。
强烈推荐Alex Martelli(和其他人)的Python
Cookbook
:
这就是字典的setdefault方法的用途。假设我们正在建立一个单词到页面编号的索引,这是一个字典,将每个单词映射到出现它的页面编号列表。该应用程序中的关键代码片段可能是:
def addword(theIndex, word, pagenumber):
theIndex.setdefault(word, [ ]).append(pagenumber)
此代码等效于更详细的方法,例如:
def addword(theIndex, word, pagenumber):
if word in theIndex:
theIndex[word].append(pagenumber)
else:
theIndex[word] = [pagenumber]
和:
def addword(theIndex, word, pagenumber):
try:
theIndex[word].append(pagenumber)
except KeyError:
theIndex[word] = [pagenumber]