0

I've got a list of strings, where each string contains a datestring in the second part, e.g.:

alist = ['foo_20150901', 'bar_20150801', 'baz_20150701']

Now I want to have them ordered ascending with respect to the date. I thought this would work like this:

slist = alist.sort(key =(lambda k: int(k.split('_')[-1])))

However, printing slist yields None. What's wrong here?

user3017048
  • 2,551
  • 3
  • 20
  • 31

3 Answers3

1

Look up the documentation for sort, it explicitly states *IN PLACE* and returning None:

Docstring: L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*
Type:      method_descriptor

To return the sorted list you need to use sorted instead:

In [5]: sorted??
Docstring:
Return a new list containing all items from the iterable in ascending order.

A custom key function can be supplied to customise the sort order, and the
reverse flag can be set to request the result in descending order.
Type:      builtin_function_or_method
Dimitris Fasarakis Hilliard
  • 136,212
  • 29
  • 242
  • 233
1

L.sort() sorts the list in-place returning None, you want the sorted function:

sorted(iterable, key=None, reverse=False)
Return a new list containing all items from the iterable in ascending order.

slist = sorted(alist, key=lambda k: int(k.split('_')[-1]))
Eugene Yarmash
  • 131,677
  • 37
  • 301
  • 358
1
alist = ['foo_20150901', 'bar_20150801', 'baz_20150701']
alist.sort(key =(lambda k: int(k.split('_')[-1])))
print alist

Output:

['baz_20150701', 'bar_20150801', 'foo_20150901']
Avión
  • 7,245
  • 9
  • 60
  • 100