search
HomeBackend DevelopmentPython TutorialA brief discussion on sorting in Python

A brief discussion on sorting in Python

Jun 21, 2017 pm 03:25 PM
pythonsortdevelopsortnotes

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 &#39;zip&#39;>
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 = {&#39;z&#39;:1, &#39;y&#39;:4,&#39;x&#39;:2,&#39;g&#39;:3,&#39;sg&#39;:3}

dic= sorted(dic.items(),key=lambda x:x[1])
print(dic)
# [(&#39;z&#39;, 1), (&#39;x&#39;, 2), (&#39;sg&#39;, 3), (&#39;g&#39;, 3), (&#39;y&#39;, 4)]

Convert to dictionary after sorting:

from collections import OrderedDict

dic = {&#39;z&#39;:1, &#39;y&#39;:4,&#39;x&#39;:2,&#39;g&#39;:3,&#39;sg&#39;:3}
dic= OrderedDict(sorted(dic.items(),key=lambda x:x[1]))

print dic
# OrderedDict([(&#39;z&#39;, 1), (&#39;x&#39;, 2), (&#39;sg&#39;, 3), (&#39;g&#39;, 3), (&#39;y&#39;, 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)
# [&#39;g&#39;, &#39;i&#39;, &#39;n&#39;, &#39;o&#39;, &#39;r&#39;, &#39;t&#39;, &#39;S&#39;, &#39;1&#39;, &#39;3&#39;, &#39;2&#39;, &#39;4&#39;]
string = &#39;&#39;.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!

Statement
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
Python and Time: Making the Most of Your Study TimePython and Time: Making the Most of Your Study TimeApr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python: Games, GUIs, and MorePython: Games, GUIs, and MoreApr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python vs. C  : Applications and Use Cases ComparedPython vs. C : Applications and Use Cases ComparedApr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

The 2-Hour Python Plan: A Realistic ApproachThe 2-Hour Python Plan: A Realistic ApproachApr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python: Exploring Its Primary ApplicationsPython: Exploring Its Primary ApplicationsApr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

How Much Python Can You Learn in 2 Hours?How Much Python Can You Learn in 2 Hours?Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics in project and problem-driven methods within 10 hours?How to teach computer novice programming basics in project and problem-driven methods within 10 hours?Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.