實現了一種模擬windows排序的python方法,其排序規則為:
- 不處理浮點數
- 特殊字元(如:&、$、# 等)排在數字和字母之前;
- 數字優先於字母排序;
- 數字是連著的整數,應該按照整數進行排序;
- 小寫字母排在大寫字母前面;
- 英文字元按字母表順序排序;
def custom_sort_key(str_value): digital_res = "" digital_flag = False sort_list = [] rank_value = [] for c in str_value: c_ascii = ord(c) if c_ascii <= 57 and c_ascii >= 48: digital_flag = True digital_res += c else: if digital_flag: digital_res = int(digital_res) rank_value.append((1, digital_res)) digital_res = "" digital_flag = False if c_ascii <= 47 or (c_ascii >= 58 and c_ascii <= 64) or (c_ascii >= 91 and c_ascii <= 96) or c_ascii >= 123: # special char rank_value.append((0, c_ascii)) elif c_ascii >= 97 and c_ascii <= 122: rank_value.append((2, c_ascii)) elif c_ascii >= 65 and c_ascii <= 90: rank_value.append((3, c_ascii)) sort_list.extend(rank_value) rank_value = [] return sort_list root_path = r"./path" image_names = os.path.listdir(root_path ) image_names = sorted(image_names, key=custom_sort_key) print(image_names)