代码之家  ›  专栏  ›  技术社区  ›  BTBts

Python3文件名的字母数字排序[重复]

  •  1
  • BTBts  · 技术社区  · 9 月前

    在python3中,我如何将myList排序为所需的顺序:

    myList = ['2', '3', '10', '4c', '4d', '4a', '4b', '5', '6', '6a', '6d', '6b', '6c', '6e', '6f', '7', '8']
    
    desiredOrder = ['2', '3', '4a', '4b', '4c', '4d', '5', '6', '6a', '6b', '6c', '6d', '6e', '6f', '7', '8', '10']
    

    事先不知道所需订单

    1 回复  |  直到 9 月前
        1
  •  1
  •   El Salceda xWF    9 月前

    排序 myList 在不事先知道顺序的情况下,您可以按照以下步骤将输出转换为所需的输出:

    1. 创建排序键: 定义一个有助于正确排序项目的关键函数。排序应首先考虑数字部分,然后考虑任何字母后缀。

    2. 排序 myList : 使用Python内置的key函数 sorted() 函数以按所需顺序获取项目。

    下面是一个逐步实现这一点的Python代码示例:

    # Define the list to be sorted
    myList = ['2', '3', '10', '4c', '4d', '4a', '4b', '5', '6', '6a', '6d', '6b', '6c', '6e', '6f', '7', '8']
    
    # Define a custom sorting key function
    def sort_key(item):
        # Extract numeric and alpha parts
        num_part = ''.join(filter(str.isdigit, item))
        alpha_part = ''.join(filter(str.isalpha, item))
        # Convert numeric part to int for proper sorting
        num_part = int(num_part) if num_part else 0
        return (num_part, alpha_part)
    
    # Sort myList using the custom key function
    sortedList = sorted(myList, key=sort_key)
    
    # Print the sorted list
    print(sortedList)
    

    说明:

    1. 自定义键功能( sort_key ):

      • 数字零件提取: 使用 filter str.isdigit 从字符串中获取数字部分并将其转换为整数。
      • 字母部分提取: 使用 滤波器 str.isalpha 获取字母部分。
      • 返回元组: 函数返回一个元组 (numeric part, alphabetic part) 这确保了排序首先按数字部分进行,如果数字部分相同,则按字母部分进行。
    2. 排序:

      • sorted(myList, key=sort_key) 使用 sort_key 用于确定项目顺序的函数 myList .

    输出

    对于给定 myList ,输出将是:

    ['2', '3', '4a', '4b', '4c', '4d', '5', '6', '6a', '6b', '6c', '6d', '6e', '6f', '7', '8', '10']
    

    这种方法将排序 myList 通过适当处理字符串的数字和字母部分,将其转换为所需的输出格式。