会php和python的大神进来帮忙转换一段代码
求把这段php代码转成python的代码,谢谢!
<code>//倒序排序 function my_sort($a,$b) { if ($a==$b) return 0; return ($a5,'bbb'=>3,'ccc'=>4); usort($arr,"my_sort"); echo json_encode($arr); </code>
简单说就是数组倒序排序,然后转成json格式。
回复内容:
求把这段php代码转成python的代码,谢谢!
<code>//倒序排序 function my_sort($a,$b) { if ($a==$b) return 0; return ($a5,'bbb'=>3,'ccc'=>4); usort($arr,"my_sort"); echo json_encode($arr); </code>
简单说就是数组倒序排序,然后转成json格式。
PHP 中的 associative array 是一種 ordered mapping (有序映射).
這代表了 Python 中的 dictionary 並非完全相等於 associative array.
其次, json 據我所知並不支援 ordered mapping,所以如果你想要完成這項任務可能要:
使用 Python 中的有序映射對象:
OrderedDict
(請參考OrderedDict)將
OrderedDict
轉為list
再轉為json
到時候要使用該項資料時,必須從
json
中 load 進list
再轉回OrderedDict
以下是 Python3 的代碼讓你參考:
代碼:
<code>import json from collections import OrderedDict # using OrderedDict arr = {"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) # list arr = list(arr.items()) print(arr) # json dump json_arr = json.dumps(arr) print(json_arr) # json load arr = OrderedDict(json.loads(json_arr)) print(arr) </code>
結果:
<code>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)]) </code>
P.S. 任何不清楚的地方都歡迎用評論告訴我,我們可以再討論
import json arr={"aaa":5,"bbb":3,"ccc":4} print json.dumps(sorted(arr.values(),reverse=True))#'[5, 4, 3]'
python代码(改造后)
<code>#!/usr/bin/env python #encoding:utf-8 import json if __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) </code>
输出:
<code>/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 </code>

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Golangisidealforbuildingscalablesystemsduetoitsefficiencyandconcurrency,whilePythonexcelsinquickscriptinganddataanalysisduetoitssimplicityandvastecosystem.Golang'sdesignencouragesclean,readablecodeanditsgoroutinesenableefficientconcurrentoperations,t

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

IIS and PHP are compatible and are implemented through FastCGI. 1.IIS forwards the .php file request to the FastCGI module through the configuration file. 2. The FastCGI module starts the PHP process to process requests to improve performance and stability. 3. In actual applications, you need to pay attention to configuration details, error debugging and performance optimization.

Laravel is suitable for projects that teams are familiar with PHP and require rich features, while Python frameworks depend on project requirements. 1.Laravel provides elegant syntax and rich features, suitable for projects that require rapid development and flexibility. 2. Django is suitable for complex applications because of its "battery inclusion" concept. 3.Flask is suitable for fast prototypes and small projects, providing great flexibility.
