Python:如何按温度与测试步数多条件排序测量文件名?
解决测量文件按温度和步数排序的问题
问题原因
你用的lsort -dict是按字典序排序,负数字符串的比较逻辑和数值不同:比如"-10"和"-20",字典序会先比较第二个字符'1'和'2',因为'1'更小,所以"-10"排在"-20"前面,不符合温度数值升序的需求。
解决方案
方案1:Python原生处理(更直观)
直接在Python中提取文件名里的温度和步数数值,用sorted函数按数值排序:
import re def get_sort_key(file_path): # 提取温度数值(匹配_-X_格式的部分) temp_match = re.search(r'_-?\d+_', file_path) temp = int(temp_match.group().strip('_')) # 提取步数数值(匹配stepX格式的部分) step_match = re.search(r'step(\d+)', file_path) step = int(step_match.group(1)) return (temp, step) # 执行排序 sorted_meas_files = sorted(meas_files, key=get_sort_key)
方案2:Tcl自定义排序命令
如果要继续用Tcl的lsort,可以通过-command选项自定义比较逻辑,提取数值后按数值大小排序:
from tkinter import Tcl tcl = Tcl() # 定义Tcl比较函数 tcl.eval(""" proc compare_meas_files {file_a file_b} { # 提取文件A的温度和步数 regexp {_-?(\d+)_} $file_a -> temp_a regexp {step(\d+)} $file_a -> step_a # 提取文件B的温度和步数 regexp {_-?(\d+)_} $file_b -> temp_b regexp {step(\d+)} $file_b -> step_b # 先比较温度 if {$temp_a < $temp_b} {return -1} if {$temp_a > $temp_b} {return 1} # 温度相同则比较步数 if {$step_a < $step_b} {return -1} if {$step_a > $step_b} {return 1} return 0 } """) # 调用Tcl排序 sorted_meas_files = list(tcl.call('lsort', '-command', 'compare_meas_files', meas_files))
两种方案都能实现:先按温度从-20到80升序,同温度下按步数从1到20升序的需求。
内容的提问来源于stack exchange,提问作者Martin
相关产品推荐
相关产品推荐

