0

This is my first time asking a question. I've already got so much help from you without even asking. (Gratitude face). So, I found this useful piece of code from around here a few weeks ago.

import re

def yearly_sort(value):
    numbers = re.compile(r'(\d+)')
    parts = numbers.split(value)
    parts[1::2] = map(int, parts[1::2])
    return parts

It works perfectly here:

def get_files_sorted(path_to_dir):
   file_names = []
   for root, dirs, files in os.walk(path_to_dir):
      for file_name in sorted(files, key=yearly_sort):
         file_names.append(os.path.join(root, file_name))
   return file_names

Now, I'm facing a problem describing the above function (as you can already see from a non-descriptive method name).

What should be the name of above method (instead of some_sort())?

Can this method be squeezed somehow in a lambda such that key in the sorted() can bind to key=lambda?

2 Answers2

2

It definitely can be lambda function. For example look at that question.

But if you have complex function you should never move it to lambda because readability significantly decreases.

So here is Zen of Python

Complex is better than complicated.

Community
  • 1
  • 1
vishes_shell
  • 22,409
  • 6
  • 71
  • 81
0

you could squeeze it into a lambda provided that numbers is previously compiled (which increases performance)

numbers = re.compile(r'(\d+)')
for file_name in sorted(files, key=lambda value : [int(x) if x.isdigit() else 0 for x in numbers.split(value)][1::2]):

In that case, we do an unnecessary test for items #0 and #3 onwards. Maybe it could be better, but that's the risk with complex lambdas: performance & lisibility can suffer.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219