Search code examples
pythonlistsortingpython-re

Python, sort with key


I am having trouble understanding key parameter in sorted function in Python. Let us say, the following list is given: sample_list = ['Date ', 'of', 'birth', 'year 1990', 'month 10', 'day 15'] and I would like to sort only the strings that contain number.

Expected output: ['Date ', 'of', 'birth', 'month 10', 'day 15', 'year 1990']

Until now, I only managed to print the string with the number

def sort_with_key(element_of_list):
    if re.search('\d+', element_of_list):
        print(element_of_list)
    return element_of_list

sorted(sample_list, key = sort_with_key)

But how do I actually sort those elements? Thank you!


Solution

  • We can try sorting with a lambda:

    sample_list = ['Date ', 'of', 'birth', 'year 1990', 'month 10', 'day 15']
    sample_list = sorted(sample_list, key=lambda x: int(re.findall(r'\d+', x)[0]) if re.search(r'\d+', x) else 0)
    print(sample_list)
    

    This prints:

    ['Date ', 'of', 'birth', 'month 10', 'day 15', 'year 1990']
    

    The logic used in the lambda is to sort by the number in each list entry, if the entry has a number. Otherwise, it assigns a value of zero to other entries, placing them first in the sort.