Sorting a list by conditional criteria
list, python, sorting
Solution
One liner solution:
mylist.sort(key=lambda x: (len(x.split())>1, x if len(x.split())==1 else int(x.split()[-1]) ) )
Explanation: First condition `len(x.split())>1` makes sure that multi word strings go behind single word strings as they will probably have numbers. So now ties will be there only between single word strings with single word strings or multi word strings with multi word strings due to first condition. Note there won't be any ties with multi word and single word strings. So if multi word string I return an integer else return string itself.
Example:
['xyz', 'keyword 1000', 'def', 'abc', 'keyword 2', 'keyword 1']
Results :
>>> mylist=['xyz', 'keyword 1000', 'def', 'abc', 'keyword 2', 'keyword 1']
>>> mylist.sort(key=lambda x: (len(x.split())>1, x if len(x.split())==1 else int(x.split()[-1]) ) )
>>> mylist
['abc', 'def', 'xyz', 'keyword 1', 'keyword 2', 'keyword 1000']
Problem
I know how to simply sort a list in Python using the `sort()` method and an appropriate lambda rule. However I don't know how to deal with the following situation : I have a list of strings, that either contain only letters or contain a specific keyword and a number. I want to sort the list first so as to put the elements with the keyword at the end, then sort those by the number they contain. e.g. my list could be: `mylist = ['abc','xyz','keyword 2','def','keyword 1']` and I want it sorted to `['abc','def','xyz','keyword 1','keyword 2']`. I already have something like ``` mylist.sort(key=lambda x: x.split("keyword")[0],reverse=True) ``` which produces only ``` ['xyz', 'def', 'abc', 'keyword 2', 'keyword 1'] ```