python backports for some methods

后端 未结 2 1914
南笙
南笙 2021-01-14 21:08

Is there any backport for the following methods to work with python 2.4:

any, all, collections.defaultdict, collections.deque
2条回答
  •  礼貌的吻别
    2021-01-14 21:26

    Well, at least for any and all it's easy:

    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 is already in 2.4.

    As for defaultdict, I guess you can emulate that easily with setdefault().

    Quoting from Alex Martelli`s (and others') highly recommended 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]
    

提交回复
热议问题