成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

掌握 Python 列表排序的 15 個方法

開發(fā) 后端
本文詳細(xì)介紹了Python中列表排序的各種方法,從基本的 sorted() 和 list.sort() 到更高級的 numpy、pandas 和自定義排序邏輯。

大家好!今天我們要聊的是Python中列表排序的各種方法。無論你是剛?cè)腴T的小白,還是有一定基礎(chǔ)的進(jìn)階者,這篇文章都會對你有所幫助。我們將從最基礎(chǔ)的方法開始,逐步深入到更高級的技巧。話不多說,讓我們開始吧!

1. 使用 sorted() 函數(shù)

sorted() 是Python內(nèi)置的一個函數(shù),可以用來對任何可迭代對象進(jìn)行排序,返回一個新的已排序列表。

# 基本用法
numbers = [5, 2, 9, 1, 5, 6]
sorted_numbers = sorted(numbers)
print(sorted_numbers)  # 輸出: [1, 2, 5, 5, 6, 9]

# 反向排序
sorted_numbers_desc = sorted(numbers, reverse=True)
print(sorted_numbers_desc)  # 輸出: [9, 6, 5, 5, 2, 1]

2. 使用 list.sort() 方法

list.sort() 是列表對象的一個方法,用于原地排序列表,不返回新的列表。

# 基本用法
numbers = [5, 2, 9, 1, 5, 6]
numbers.sort()
print(numbers)  # 輸出: [1, 2, 5, 5, 6, 9]

# 反向排序
numbers.sort(reverse=True)
print(numbers)  # 輸出: [9, 6, 5, 5, 2, 1]

3. 按字符串長度排序

有時候我們需要按字符串的長度進(jìn)行排序,這可以通過 key 參數(shù)來實(shí)現(xiàn)。

words = ["apple", "banana", "cherry", "date"]
sorted_words_by_length = sorted(words, key=len)
print(sorted_words_by_length)  # 輸出: ['date', 'apple', 'cherry', 'banana']

4. 按自定義函數(shù)排序

我們可以使用 key 參數(shù)傳入一個自定義函數(shù),以實(shí)現(xiàn)更復(fù)雜的排序邏輯。

def custom_key(word):
    return word[-1]  # 按最后一個字符排序

words = ["apple", "banana", "cherry", "date"]
sorted_words_custom = sorted(words, key=custom_key)
print(sorted_words_custom)  # 輸出: ['date', 'apple', 'banana', 'cherry']

5. 按多個條件排序

有時我們需要按多個條件進(jìn)行排序,這可以通過傳遞一個元組作為 key 參數(shù)來實(shí)現(xiàn)。

students = [
    {"name": "Alice", "age": 20},
    {"name": "Bob", "age": 22},
    {"name": "Charlie", "age": 20}
]

# 先按年齡排序,再按名字排序
sorted_students = sorted(students, key=lambda x: (x['age'], x['name']))
print(sorted_students)
# 輸出: [{'name': 'Alice', 'age': 20}, {'name': 'Charlie', 'age': 20}, {'name': 'Bob', 'age': 22}]

6. 按數(shù)值絕對值排序

有時我們需要按數(shù)值的絕對值進(jìn)行排序,這同樣可以通過 key 參數(shù)來實(shí)現(xiàn)。

numbers = [-5, 2, -1, 3, 0, -2]
sorted_numbers_abs = sorted(numbers, key=abs)
print(sorted_numbers_abs)  # 輸出: [0, -1, 2, -2, 3, -5]

7. 按對象屬性排序

如果列表中的元素是對象,我們可以按對象的某個屬性進(jìn)行排序。

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

people = [
    Person("Alice", 20),
    Person("Bob", 22),
    Person("Charlie", 20)
]

# 按年齡排序
sorted_people = sorted(people, key=lambda x: x.age)
for person in sorted_people:
    print(person.name, person.age)
# 輸出: Alice 20, Charlie 20, Bob 22

8. 使用 operator.attrgetter 和 operator.itemgetter

operator 模塊提供了 attrgetter 和 itemgetter 函數(shù),可以簡化按屬性或鍵值排序的操作。

from operator import attrgetter, itemgetter

# 按對象屬性排序
sorted_people_attr = sorted(people, key=attrgetter('age'))
for person in sorted_people_attr:
    print(person.name, person.age)
# 輸出: Alice 20, Charlie 20, Bob 22

# 按字典鍵值排序
students = [
    {"name": "Alice", "age": 20},
    {"name": "Bob", "age": 22},
    {"name": "Charlie", "age": 20}
]

sorted_students_item = sorted(students, key=itemgetter('age'))
print(sorted_students_item)
# 輸出: [{'name': 'Alice', 'age': 20}, {'name': 'Charlie', 'age': 20}, {'name': 'Bob', 'age': 22}]

9. 使用 heapq.nsmallest 和 heapq.nlargest

heapq 模塊提供了 nsmallest 和 nlargest 函數(shù),可以快速找到列表中的最小或最大元素。

import heapq

numbers = [5, 2, 9, 1, 5, 6]

# 找到前3個最小的數(shù)
smallest_three = heapq.nsmallest(3, numbers)
print(smallest_three)  # 輸出: [1, 2, 5]

# 找到前3個最大的數(shù)
largest_three = heapq.nlargest(3, numbers)
print(largest_three)  # 輸出: [9, 6, 5]

10. 使用 pandas 庫排序

如果你處理的是數(shù)據(jù)科學(xué)相關(guān)的任務(wù),pandas 庫提供了強(qiáng)大的數(shù)據(jù)處理功能,包括排序。

import pandas as pd

data = {
    'name': ['Alice', 'Bob', 'Charlie'],
    'age': [20, 22, 20]
}

df = pd.DataFrame(data)

# 按年齡排序
sorted_df = df.sort_values(by='age')
print(sorted_df)
# 輸出:
#       name  age
# 0   Alice   20
# 2  Charlie  20
# 1     Bob   22

11. 使用 numpy 庫排序

numpy 是一個強(qiáng)大的科學(xué)計(jì)算庫,它提供了高效的數(shù)組操作功能,包括排序。

import numpy as np

numbers = [5, 2, 9, 1, 5, 6]
np_numbers = np.array(numbers)

# 升序排序
sorted_np_numbers = np.sort(np_numbers)
print(sorted_np_numbers)  # 輸出: [1 2 5 5 6 9]

# 降序排序
sorted_np_numbers_desc = np.sort(np_numbers)[::-1]
print(sorted_np_numbers_desc)  # 輸出: [9 6 5 5 2 1]

12. 自定義比較函數(shù)

在某些情況下,我們需要更復(fù)雜的排序邏輯,可以使用 functools.cmp_to_key 將自定義的比較函數(shù)轉(zhuǎn)換為 key 函數(shù)。

from functools import cmp_to_key

def custom_compare(x, y):
    if x < y:
        return -1
    elif x > y:
        return 1
    else:
        return 0

numbers = [5, 2, 9, 1, 5, 6]
sorted_numbers_custom = sorted(numbers, key=cmp_to_key(custom_compare))
print(sorted_numbers_custom)  # 輸出: [1, 2, 5, 5, 6, 9]

13. 穩(wěn)定排序

穩(wěn)定排序是指在排序過程中,相同元素的相對位置保持不變。sorted() 和 list.sort() 都是穩(wěn)定的排序算法。

students = [
    {"name": "Alice", "age": 20},
    {"name": "Bob", "age": 22},
    {"name": "Charlie", "age": 20}
]

# 先按名字排序,再按年齡排序
students.sort(key=lambda x: x['name'])
students.sort(key=lambda x: x['age'])

for student in students:
    print(student['name'], student['age'])
# 輸出: Alice 20, Charlie 20, Bob 22

在這個例子中,先按名字排序,再按年齡排序,保證了相同年齡的學(xué)生的名字順序不變。

14. 多級排序(使用 pandas)

pandas 庫不僅支持單級排序,還支持多級排序。

import pandas as pd

data = {
    'name': ['Alice', 'Bob', 'Charlie', 'David'],
    'age': [20, 22, 20, 21],
    'score': [85, 90, 88, 92]
}

df = pd.DataFrame(data)

# 先按年齡升序排序,再按分?jǐn)?shù)降序排序
sorted_df = df.sort_values(by=['age', 'score'], ascending=[True, False])
print(sorted_df)
# 輸出:
#      name  age  score
# 0   Alice   20     85
# 2  Charlie  20     88
# 3   David   21     92
# 1     Bob   22     90

15. 使用 itertools.groupby 進(jìn)行分組排序

itertools.groupby 可以將列表按某個條件分組,然后再對每個組進(jìn)行排序。

from itertools import groupby

students = [
    {"name": "Alice", "age": 20},
    {"name": "Bob", "age": 22},
    {"name": "Charlie", "age": 20},
    {"name": "David", "age": 21}
]

# 先按年齡排序
students.sort(key=lambda x: x['age'])

# 按年齡分組
grouped_students = {k: list(v) for k, v in groupby(students, key=lambda x: x['age'])}

for age, group in grouped_students.items():
    print(f"Age: {age}")
    for student in group:
        print(student['name'], student['age'])
# 輸出:
# Age: 20
# Alice 20
# Charlie 20
# Age: 21
# David 21
# Age: 22
# Bob 22

實(shí)戰(zhàn)案例分析

假設(shè)你是一家在線書店的開發(fā)人員,需要對書籍按評分和銷量進(jìn)行排序。我們將使用前面學(xué)到的多種排序方法來實(shí)現(xiàn)這個需求。

books = [
    {"title": "Book A", "rating": 4.5, "sales": 500},
    {"title": "Book B", "rating": 4.2, "sales": 300},
    {"title": "Book C", "rating": 4.7, "sales": 700},
    {"title": "Book D", "rating": 4.3, "sales": 400}
]

# 先按評分降序排序,再按銷量降序排序
sorted_books = sorted(books, key=lambda x: (-x['rating'], -x['sales']))

for book in sorted_books:
    print(book['title'], book['rating'], book['sales'])
# 輸出:
# Book C 4.7 700
# Book A 4.5 500
# Book D 4.3 400
# Book B 4.2 300

在這個案例中,我們使用了 lambda 表達(dá)式和 key 參數(shù)來實(shí)現(xiàn)多級排序。希望這個案例能幫助你更好地理解和應(yīng)用這些排序方法。

總結(jié)

本文詳細(xì)介紹了Python中列表排序的各種方法,從基本的 sorted() 和 list.sort() 到更高級的 numpy、pandas 和自定義排序邏輯。通過這些方法,你可以靈活地應(yīng)對各種排序需求。

責(zé)任編輯:趙寧寧 來源: 手把手PythonAI編程
相關(guān)推薦

2025-01-03 08:48:20

列表推導(dǎo)式Python編程

2009-11-20 09:24:10

PHP多維數(shù)組排序

2020-10-30 08:58:33

Python列表開發(fā)

2024-07-03 10:31:21

2023-10-04 00:02:00

本文將從入門到精通,冒泡排序

2024-06-28 09:52:47

列表Python

2021-09-27 10:07:39

Python 開發(fā)編程語言

2024-05-13 09:06:15

代碼PythonPEP 8

2011-02-17 14:43:29

Windows 7加速

2021-06-24 17:55:40

Python 開發(fā)編程語言

2023-07-04 15:52:49

JavaScript數(shù)組

2009-06-26 10:10:00

Hibernate狀態(tài)

2024-02-22 15:31:46

Python排序

2020-03-19 15:30:08

JavaScript數(shù)組字符串

2024-05-20 10:00:00

代碼Python編程

2022-04-28 10:47:09

漏洞網(wǎng)絡(luò)安全網(wǎng)絡(luò)攻擊

2024-12-17 17:20:00

Python列表

2024-12-23 08:10:00

Python代碼性能代碼

2024-11-27 06:46:47

Python列表推導(dǎo)式嵌套邏輯

2022-04-28 08:41:53

JavaScript數(shù)組
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號

主站蜘蛛池模板: 国产91亚洲精品一区二区三区 | 亚洲欧洲在线视频 | 精品一区二区三区四区五区 | 91亚洲免费 | 久久夜色精品国产 | 欧美在线一区二区视频 | 毛片99 | 久久亚洲综合 | 视频一区在线观看 | 日韩精品成人 | 中文字幕亚洲在线 | 在线看91 | 日韩国产中文字幕 | 欧美影院 | 亚洲国产精品一区二区久久 | 日韩伦理一区二区 | 在线观看成年人视频 | 亚洲精品乱码久久久久久按摩观 | 91精品在线播放 | 精品1区| 久久久久久天堂 | 日本黄视频在线观看 | 在线观看日韩精品视频 | 日韩欧美久久精品 | 久久亚洲一区 | 国产乱码精品1区2区3区 | 国产成人精品一区二 | 国产精品一区在线 | 亚洲v日韩v综合v精品v | 天天插天天操 | 欧美理论 | 美女一级毛片 | 久久一区二区三区四区五区 | 欧美激情亚洲天堂 | 国产丝袜一区二区三区免费视频 | 91精品麻豆日日躁夜夜躁 | 国产精品视频网址 | 成av在线| 黄色av网站在线观看 | 特级丰满少妇一级aaaa爱毛片 | 成人区精品一区二区婷婷 |