Table of Contents
回复内容:
Home Backend Development PHP Tutorial 会php和python的大神进来帮忙转换一段代码

会php和python的大神进来帮忙转换一段代码

Jun 06, 2016 pm 08:09 PM
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>
Copy after login
Copy after login

简单说就是数组倒序排序,然后转成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>
Copy after login
Copy after login

简单说就是数组倒序排序,然后转成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 的代碼讓你參考:

代碼:

<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>
Copy after login

結果:

<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>
Copy after login

P.S. 任何不清楚的地方都歡迎用評論告訴我,我們可以再討論

import json
arr={"aaa":5,"bbb":3,"ccc":4}
print json.dumps(sorted(arr.values(),reverse=True))#'[5, 4, 3]'
Copy after login

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>
Copy after login

输出:

<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>
Copy after login

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24
Golang vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 19, 2025 am 12:18 AM

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.

The Continued Use of PHP: Reasons for Its Endurance The Continued Use of PHP: Reasons for Its Endurance Apr 19, 2025 am 12:23 AM

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 vs. C  : Learning Curves and Ease of Use Python vs. C : Learning Curves and Ease of Use Apr 19, 2025 am 12:20 AM

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.

Python vs. JavaScript: Development Environments and Tools Python vs. JavaScript: Development Environments and Tools Apr 26, 2025 am 12:09 AM

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.

Golang vs. Python: The Pros and Cons Golang vs. Python: The Pros and Cons Apr 21, 2025 am 12:17 AM

Golangisidealforbuildingscalablesystemsduetoitsefficiencyandconcurrency,whilePythonexcelsinquickscriptinganddataanalysisduetoitssimplicityandvastecosystem.Golang'sdesignencouragesclean,readablecodeanditsgoroutinesenableefficientconcurrentoperations,t

Python vs. C  : Understanding the Key Differences Python vs. C : Understanding the Key Differences Apr 21, 2025 am 12:18 AM

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.

The Compatibility of IIS and PHP: A Deep Dive The Compatibility of IIS and PHP: A Deep Dive Apr 22, 2025 am 12:01 AM

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 vs. Python (with Frameworks): A Comparative Analysis Laravel vs. Python (with Frameworks): A Comparative Analysis Apr 21, 2025 am 12:15 AM

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.

See all articles