會php和python的大神進來幫忙轉換一段代碼

來源:互聯網
上載者:User
關鍵字 php python
求把這段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,所以如果你想要完成這項任務可能要:

  1. 使用 Python 中的有序映射對象: OrderedDict (請參考OrderedDict)

  2. OrderedDict 轉為 list 再轉為 json

  3. 到時候要使用該項資料時,必須從 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
  • 相關文章

    聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.