求把这段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格式。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
PHP 中的 associative array 是一種 ordered mapping (有序映射).
這代表了 Python 中的 dictionary 並非完全相等於 associative array.
其次, json 據我所知並不支援 ordered mapping,所以如果你想要完成這項任務可能要:
使用 Python 中的有序映射對象:
OrderedDict(請參考OrderedDict)將
OrderedDict轉為list再轉為json到時候要使用該項資料時,必須從
json中 load 進list再轉回OrderedDict以下是 Python3 的代碼讓你參考:
代碼:
結果:
P.S. 任何不清楚的地方都歡迎用評論告訴我,我們可以再討論
python代码(改造后)
输出: