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
. "
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.
Use slice notation [length-2:] to Get the last two characters of string Python.
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.
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With