A brief discussion on sorting in Python
A brief talk about sorting
Sorting functions are often used in programs. Python provides sort and sorted functions, one for sorting in place and the other for returning the new result after sorting
1. Parameters
##Function prototype:
sort([cmp[, key[, reverse]]])
means that the sort method accepts three parameters, all of which can be omitted. The default is ascending order.
The first parameter cmp is a comparison function. How to compare two parameters (elements of a list)? For comparison of built-in types such as integers, the method is very intuitive. , but for comparisons of custom types, you have to define the comparison function yourself. The function returns 0, which means the two numbers are equal, and returns a negative number, which means the first parameter is smaller, and the first parameter is ranked behind the second parameter. .
#The second parameter key is the attribute of the comparison list element.
The third parameter reverse is of type bool, which means whether to reverse (sort in reverse order)
①, cmp parameter example:
#cmp 函数,两个数倒过来比较 注!只能在python2.0上运行 s = [1, 2, 3, 4, 5] s.sort(cmp=lambda a, b:cmp(b, a)) print s # [5, 4, 3, 2, 1]
②, Common parameter key, reverse usage method , Code:
# key 指定排序方式 reverse 是否反排序 li = ['x11','abc323','e26','112ddd','fstgd2'] li.sort(key=len,reverse=True) # 用长度进行排序,从大到小进行排序 print(li) # ['abc323', '112ddd', 'fstgd2', 'x11', 'e26'] li.sort(key=lambda x:x[-1]) # key可以指定lambada函数x为列表中每个元素 print(li) # 元素的最后一个字符进行排序 # ['x11', 'fstgd2', 'abc323', 'e26', '112ddd'] li = zip(range(10),range(10)[::-1]) # 列表中元素为元祖是排序 print(li,type(li)) # <zip object at 0x000000E7F75504C8> <class 'zip'> li = list(li) print(li) # [(0, 9), (1, 8), (2, 7), (3, 6), (4, 5), (5, 4), (6, 3), (7, 2), (8, 1), (9, 0)] li.sort(key=lambda x:x[-1]) print(li) # [(9, 0), (8, 1), (7, 2), (6, 3), (5, 4), (4, 5), (3, 6), (2, 7), (1, 8), (0, 9)] #**注!默认sort也是会对列表中元祖进行排序的 li.sort() print(li) # (0, 9), (1, 8), (2, 7), (3, 6), (4, 5), (5, 4), (6, 3), (7, 2), (8, 1), (9, 0)]
The parameter key can be: key=int, key=len, key=lambda...
2. Sorting
①. How to output the keys in the dict from small to large according to value- value?
dic = {'z':1, 'y':4,'x':2,'g':3,'sg':3} dic= sorted(dic.items(),key=lambda x:x[1]) print(dic) # [('z', 1), ('x', 2), ('sg', 3), ('g', 3), ('y', 4)]
Convert to dictionary after sorting:
from collections import OrderedDict dic = {'z':1, 'y':4,'x':2,'g':3,'sg':3} dic= OrderedDict(sorted(dic.items(),key=lambda x:x[1])) print dic # OrderedDict([('z', 1), ('x', 2), ('sg', 3), ('g', 3), ('y', 4)]) for k,v in dic.items(): print k,v # z 1 # x 2 # sg 3 # g 3 # y 4
②,Given a string containing only uppercase and lowercase letters and numbers, sort it to ensure:
All lowercase letters come before uppercase letters
All letters come before numbers
All odd numbers come before even numbers
s = "Sorting1234" def sort_str(x): # x 传入的每个元素 if x.isdigit(): if int(x) % 2 == 0: return (4,x) # 返回的是元祖,元祖可进行排序 return (3,x) elif x.islower(): return (0,x) elif x.isupper(): return (1,x) li = sorted(s,key=sort_str) print(li) # ['g', 'i', 'n', 'o', 'r', 't', 'S', '1', '3', '2', '4'] string = ''.join(li) print(string) # ginortS1324
More concise code:
s = "Sorting1234" s ="".join(sorted(s, key=lambda x: (x.isdigit(), x.isdigit() and int(x) % 2 == 0, x.isupper(), x.islower(), x))) print(s) # ginortS1324
The above is the detailed content of A brief discussion on sorting in Python. For more information, please follow other related articles on the PHP Chinese website!

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

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".
