猿问

有没有人遇到过这个问题哈!对json数组排序,python

问题描述我有这样一个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"}]请问我改如何进行处理
繁花如伊
浏览 299回答 2
2回答

料青山看我应如是

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
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答