简体   繁体   中英

how to write a sorted function in python for version before 2.4

I am unfortunately having to use python with version before 2.4 So I don't have the sorted built-in function. I need to sort a list; I found it is not possibly to go with

for aName in mylist.sort(lambda x,y:cmp(x.getName,y.getName)):

because then I would get an error saying

TypeError: iteration over non-sequence

I want to do the following:

for aName in sorted(mylist,key=lambda x:x.getName):

Can anybody help me with this? Many thanks.

You said that you wanted to do for aName in sorted(mylist,key=lambda x:x.getName): but accepted an answer that did something else ...

It's quite possible to write code that will run on multiple versions of Python 2.x. Here's how to retrofit sorted() functionality to Python 2.1 to 2.3. It uses the DSU (decorate-sort-undecorate) aka "Schwartzian Transform" method ... see this section of the Sorting HOWTO but do read the whole HOWTO; it's very informative.

try:
    sorted
    def mysorted(iterable, key, reverse=0):
        return sorted(iterable, key=key, reverse=reverse)
except NameError: # doesn't have "sorted"
    def mysorted(iterable, key, reverse=0):
        temp = [(key(x), x) for x in iterable]
        temp.sort()
        if reverse:
            return [temp[i][1] for i in xrange(len(temp) - 1, -1, -1)]
        return [t[1] for t in temp]

mylist = 'tom dick harriet alfred zechariah'.split()
mykey = lambda x: x[2:] # ignore 1st 2 characters
print mylist
print mysorted(mylist, mykey)
print mysorted(mylist, mykey, reverse=1)

Running the above script with Python 2.7.1 and 2.1.3 produces the same output:

['tom', 'dick', 'harriet', 'alfred', 'zechariah']
['zechariah', 'dick', 'alfred', 'tom', 'harriet']
['harriet', 'tom', 'alfred', 'dick', 'zechariah']
mylist.sort(lambda x,y:cmp(x.getName,y.getName))
for aName in mylist:
  ...

list.sort sorts in-place and doesn't have return value.

def sorted(iter, **rest):
    temp = list(iter)
    temp.sort(**rest)
    return temp

I think that should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM