How do you sort files numerically?

前端 未结 6 1230
一生所求
一生所求 2020-11-28 07:01

First off, I\'m posting this because when I was looking for a solution to the problem below, I could not find one on stackoverflow. So, I\'m hoping to add a little bit to t

6条回答
  •  半阙折子戏
    2020-11-28 07:46

    If you are using key= in your sort method you shouldn't use cmp which has been removed from the latest versions of Python. key should be equated to a function which takes a record as input and returns any object which will compare in the order you want your list sorted. It doesn't need to be a lambda function and might be clearer as a stand alone function. Also regular expressions can be slow to evaluate.

    You could try something like the following to isolate and return the integer part of the file name:

    def getint(name):
        basename = name.partition('.')
        alpha, num = basename.split('_')
        return int(num)
    tiffiles.sort(key=getint)
    

提交回复
热议问题