按某个属性排序(字典序,ascII) js/python
javascrapy方法
var compare = (prop)=>{ return (a,b)=>{ return a[prop]>b[prop] ? 1 : -1 } }
javascrapy测试代码
var aaa = [ {name: "total_amount", value: 10}, {name: "nonce_str", value: "1"}, {name: "mch_billno", value: "1"}, {name: "act_name", value: "1"}, {name: "client_ip", value: "1"}, {name: "mch_id", value: "1"}, {name: "re_openid", value: "1"}, {name: "remark", value: "1"}, {name: "scene_id", value: "1"}, {name: "send_name", value: "1"}, {name: "total_num", value: 1}, {name: "wishing", value: "1"}, {name: "wxappid", value: "1"} ] console.dir(aaa.sort(compare('name')))
javascrapy测试结果
升序写的有点问题,后续补,直接返回true false也不能得到正确结果
python写法
props = { 'b': 1, 'a': 2, '2fdsadf': 'fafafa', 'a1': 'afafa' } print sorted(props.items()) print sorted(props)
执行结果
[('2fdsadf', 'fafafa'), ('a', 2), ('a1', 'afafa'), ('b', 1)] -------------------- ['2fdsadf', 'a', 'a1', 'b']
数据顺序都对了,按需取就行了
Become a Linux Programmer