Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a list of strings by last N characters in Python 2.3

In newer Python, I am able to use the sorted function and easily sort out a list of strings according to their last few chars as such:

lots_list = ['anything']

print sorted(lots_list, key=returnlastchar)

def returnlastchar(s):     
    return s[10:] 

How can I implement the above to lots_list.sort() in older Python (2.3)?

" Error: When I tried using sorted(), the global name sorted is not defined. "

like image 711
Poker Prof Avatar asked Jul 03 '12 03:07

Poker Prof


People also ask

How do I sort a list by last character of string?

You can sort using a function, here we use the lambda function which looks at the last index of the strings inside of your list. Without making a copy of the list you can apply the . sort() . This is a more memory efficient method.

How do I get the last two characters of a string in Python?

Use slice notation [length-2:] to Get the last two characters of string Python.

How do I sort a list in Python 2?

sort() is one of Python's list methods for sorting and changing a list. It sorts list elements in either ascending or descending order. sort() accepts two optional parameters. reverse is the first optional parameter.

How do you sort a list of strings in Python without sorting?

You can use Nested for loop with if statement to get the sort a list in Python without sort function. This is not the only way to do it, you can use your own logic to get it done.


1 Answers

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

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]
like image 126
John La Rooy Avatar answered Nov 07 '22 20:11

John La Rooy