问题描述我有这样一个json数组a=[{"id":863,"hostname":"hdfs"},{"id":822,"hostname":"admin"},{"id":865,"hostname":"Spark-1"},{"id":1074,"hostname":"Spark-10"},{"id":867,"hostname":"Spark-2"},{"id":1014,"hostname":"Spark-11"}]通过sort按hostname字段排序a.sort(key=lambdax:x["hostname"])得到的是这样的结果Spark-10在Spark-2前面[{"id":822,"hostname":"admin"},{"id":863,"hostname":"hdfs"},{"id":865,"hostname":"Spark-1"},{"id":1074,"hostname":"Spark-10"},{"id":1014,"hostname":"Spark-11"},{"id":867,"hostname":"Spark-2"},]而我希望得到这样一个结果[{"id":822,"hostname":"admin"},{"id":863,"hostname":"hdfs"},{"id":865,"hostname":"Spark-1"},{"id":867,"hostname":"Spark-2"},{"id":1074,"hostname":"Spark-10"},{"id":1014,"hostname":"Spark-11"}]请问我改如何进行处理
2 回答
料青山看我应如是
TA贡献1772条经验 获得超8个赞
1、取当前列表出现的数字的最大长度2、把出现的数字的字符串进行补0操作importredefget_number(s):re_digits=re.compile('(\d+)')returnre_digits.search(s).group(1)ifre_digits.search(s)elseNonedefzfill(s,width):number=get_number(s)ifnumber:s=s.replace(number,number.zfill(width))returns.lower()lst=[{"id":863,"hostname":"hdfs"},{"id":822,"hostname":"admin"},{"id":111,"hostname":"test2"},{"id":222,"hostname":"test11"},{"id":865,"hostname":"Spark-1"},{"id":1074,"hostname":"Spark-10"},{"id":867,"hostname":"Spark-2"},{"id":1014,"hostname":"Spark-11"}]max_width=int(max([get_number(_['hostname'])for_inlst]))lst.sort(key=lambdax:zfill(x['hostname'],max_width))printlst
添加回答
举报
0/150
提交
取消