gpt4 book ai didi

某些方法的 python backports

转载 作者:行者123 更新时间:2023-11-28 19:59:35 24 4
gpt4 key购买 nike

是否有以下方法可以与 python 2.4 一起使用的任何反向移植:

any, all, collections.defaultdict, collections.deque

最佳答案

好吧,至少对于 anyall 这很简单:

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 :

This is what the setdefault method of dictionaries is for. Say we’re building a word-to-page-numbers index, a dictionary that maps each word to the list of page numbers where it appears. A key piece of code in that application might be:

def addword(theIndex, word, pagenumber):
theIndex.setdefault(word, [ ]).append(pagenumber)

This code is equivalent to more verbose approaches such as:

def addword(theIndex, word, pagenumber):
if word in theIndex:
theIndex[word].append(pagenumber)
else:
theIndex[word] = [pagenumber]

and:

def addword(theIndex, word, pagenumber):
try:
theIndex[word].append(pagenumber)
except KeyError:
theIndex[word] = [pagenumber]

关于某些方法的 python backports,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3785433/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com