zoukankan      html  css  js  c++  java
  • python实现根据图像路径排序

    • 实现功能:输入为图像路径列表,根据图像名称中的数字大小实现图像路径的排序
    from functools import cmp_to_key
    
    def get_suffix(filename):
        """a.jpg -> jpg"""
        pos = filename.rfind('.')
        if pos == -1:
            return ''
        return filename[pos:]
    
    '''
    求两个字符串的最长公共子串
    思想:建立一个二维数组,保存连续位相同与否的状态
    '''
    def get_num_of_common_substr(str1, str2):
      
     lstr1 = len(str1)
     lstr2 = len(str2)
     record = [[0 for i in range(lstr2+1)] for j in range(lstr1+1)] # 多一位
     maxNum = 0   # 最长匹配长度
     p = 0    # 匹配的起始位
      
     for i in range(lstr1):
      for j in range(lstr2):
       if str1[i] == str2[j] and not str1[i].isdigit():
        # 相同则累加
        record[i+1][j+1] = record[i][j] + 1
        if record[i+1][j+1] > maxNum:
         # 获取最大匹配长度
         maxNum = record[i+1][j+1]
         # 记录最大匹配长度的终止位置
         p = i + 1
     return str1[p-maxNum:p]
    
    #给出一个绝对路径格式 .../.../color1.png .../.../color20.png 找到图像名中数字的位置,比较数字大小
    def sort_by_index(str1,str2):
        suffix = get_suffix(str1)   
        str_1 = str1.split("/")[-1].replace(f'{suffix}',"")
        str_2 = str2.split("/")[-1].replace(f'{suffix}',"")  
        sub_str = get_num_of_common_substr(str_1,str_2)   
        int_str1 = int(str_1.replace(f'{sub_str}',"")) if len(str_1.replace(f'{sub_str}',"")) else 0
        int_str2 = int(str_2.replace(f'{sub_str}',"")) if len(str_2.replace(f'{sub_str}',"")) else 0
        return int_str1-int_str2
    
    if __name__ == '__main__':
        str_list = ["a/b/c/color15.png","a/b/c/color2.png","a/b/c/color13.png","a/b/c/color1.png"]
        str_list.sort(key=cmp_to_key(sort_by_index))
        print(str_list)
    
    
  • 相关阅读:
    自定义DelegatingHandler为ASP.NET Web Api添加压缩与解压的功能
    搭建Linux环境--部署discuzx论坛
    搭建Linux环境--安装PHP
    搭建Linux环境--安装Apache
    搭建Linux环境--安装MySQL
    搭建Linux环境--安装tomcat
    搭建Linux环境--安装jdk
    vmware中安装了contes--解决ifconfig无法执行
    设计模式(四)原型模式
    设计模式(三)建造者模式
  • 原文地址:https://www.cnblogs.com/jiajiewu/p/13913365.html
Copyright © 2011-2022 走看看