Home > Software engineering >  Python, sort with key
Python, sort with key

Time:12-10

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!

CodePudding user response:

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.

CodePudding user response:

If I understand correctly, you want strings with a number to be sorted with this number as key, and strings without a number to be at the beginning?

You need a key that extracts the number from the string. We can use str.isdigit() to extract digits from a string, ''.join() to put these digits back together, and int() to convert to an integer. If there are no digits in the string, we'll return -1 instead, so it comes before all nonnegative numbers.

sample_list = ['Date ', 'of', 'birth', 'year 1990', 'month 10', 'day 15', 'answer 42', 'small number 0', 'large number 8676965', 'no number here']

sample_list.sort(key=lambda s: int(''.join(c for c in s if c.isdigit()) or -1))

print(sample_list)
# ['Date ', 'of', 'birth', 'no number here', 'small number 0', 'month 10', 'day 15', 'answer 42', 'year 1990', 'large number 8676965']
  • Related