求把這段php代碼轉成python的代碼,謝謝!
//倒序排序function my_sort($a,$b){ if ($a==$b) return 0; return ($a<$b)?1:-1;}$arr = array('aaa'=>5,'bbb'=>3,'ccc'=>4);usort($arr,"my_sort");echo json_encode($arr);
簡單說就是數組倒序排序,然後轉成json格式。
回複內容:
求把這段php代碼轉成python的代碼,謝謝!
//倒序排序function my_sort($a,$b){ if ($a==$b) return 0; return ($a<$b)?1:-1;}$arr = array('aaa'=>5,'bbb'=>3,'ccc'=>4);usort($arr,"my_sort");echo json_encode($arr);
簡單說就是數組倒序排序,然後轉成json格式。
PHP 中的 associative array 是一種 ordered mapping (有序映射).
這代表了 Python 中的 dictionary 並非完全相等於 associative array.
其次, json 據我所知並不支援 ordered mapping,所以如果你想要完成這項任務可能要:
使用 Python 中的有序映射對象: OrderedDict
(請參考OrderedDict)
將 OrderedDict
轉為 list
再轉為 json
到時候要使用該項資料時,必須從 json
中 load 進 list
再轉回 OrderedDict
以下是 Python3 的代碼讓你參考:
代碼:
import jsonfrom collections import OrderedDict# using OrderedDictarr = {"aaa":5,"bbb":3,"ccc":4, "ddd":7}arr = OrderedDict(sorted(arr.items(), key=lambda item: item[1], reverse=True))# or you can create an OrderedDict directly:# arr = OrderedDict([('aaa', 5), ('bbb', 3), ('ccc', 4), ('ddd', 7)])print(arr)# listarr = list(arr.items())print(arr)# json dumpjson_arr = json.dumps(arr)print(json_arr)# json loadarr = OrderedDict(json.loads(json_arr))print(arr)
結果:
OrderedDict([('ddd', 7), ('aaa', 5), ('ccc', 4), ('bbb', 3)])[('ddd', 7), ('aaa', 5), ('ccc', 4), ('bbb', 3)][["ddd", 7], ["aaa", 5], ["ccc", 4], ["bbb", 3]]OrderedDict([('ddd', 7), ('aaa', 5), ('ccc', 4), ('bbb', 3)])
P.S. 任何不清楚的地方都歡迎用評論告訴我,我們可以再討論
import jsonarr={"aaa":5,"bbb":3,"ccc":4}print json.dumps(sorted(arr.values(),reverse=True))#'[5, 4, 3]'
python代碼(改造後)
#!/usr/bin/env python#encoding:utf-8import jsonif __name__ == '__main__': myDict = {'aaa':5,'bbb':6,'ccc':777} outDic = sorted(myDict.iteritems(), key=lambda asd: asd[1], reverse=True) print '排序前的字典,類似於php的array' print myDict print '排序後json輸出:' print json.dumps(outDic)
輸出:
/System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7 /Users/luyh/www/python/lesson1/pysort.py排序前的字典,類似於php的array{'aaa': 5, 'bbb': 6, 'ccc': 777}排序後json輸出:[["ccc", 777], ["bbb", 6], ["aaa", 5]]Process finished with exit code 0