Python Sort Recent Characters

In new Python, I can use a sorted function and easily sort the list of strings according to their last few characters as such:

lots_list=['anything'] print sorted(lots_list, key=returnlastchar) def returnlastchar(s): return s[10:] 

How can I implement above to lots_list.sort() , which is used in earlier Python (2.3)?

"Error: when I tried to use sorted() , the global name sorted is not defined ."

Thanks!

+6
source share
4 answers

I don't have python 2.3 at hand, however, according to this post Sorting a list of lists by item frequency in Python 2.3 http://docs.python.org/release/2.3/lib/typesseq-mutable.html this method should also work for you .

 def mycmp(a, b): return cmp(a[10:], b[10:]) lots_list.sort(mycmp) 
+5
source

the Schwartz transform is usually more efficient than using the cmp argument (this is what newer versions of Python do when using key )

 lots_list=['anything'] def returnlastchar(s): return s[10:] decorated = [(returnlastchar(s), s) for s in lots_list] decorated.sort() lots_list = [x[1] for x in decorated] 
+8
source

It's easy to write your own version of sorting. The following is the replacement (excluding the paramagnetic cmp block):

 def _count(): i = 0 while 1: yield i i += 1 def sorted(iterable, key=None, reverse=False): 'Drop-in replacement for the sorted() built-in function (excluding cmp())' seq = list(iterable) if reverse: seq.reverse() if key is not None: seq = zip(map(key, seq), _count(), seq) seq.sort() if key is not None: seq = map(lambda decorated: decorated[2], seq) if reverse: seq.reverse() return seq 
+1
source

You can write your own sorted() like this:

 try: sorted except NameError: def sorted(seq, key=None): lst = list(seq) # get copy of list if key is not None: def my_cmp(a, b): return cmp(key(a), key(b)) else: my_cmp = cmp lst.sort(my_cmp) return lst 

This will only determine your new sorted() if there is no built-in sorted() . First, we try to evaluate the name sorted , and if we get a NameError , we define our own. I use map(None, seq) as a quick way to make a new list from seq values.

Or, if we want to use the Schwartzian Transform for maximum efficiency, as suggested by @gnibbler:

 try: sorted except NameError: import operator as op def sorted(seq, key=None): if key is not None: lst = [(key(x), x) for x in seq] lst.sort() return map(lambda x: x[1], lst) else: lst = list(seq) # get list from sequence lst.sort() return lst 
0
source

Source: https://habr.com/ru/post/919546/


All Articles