最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python之sorted函數(shù)使用與實戰(zhàn)過程

 更新時間:2026年02月03日 09:14:06   作者:alden_ygq  
本文詳細(xì)介紹了Python中`sorted()`函數(shù)的用法,包括基礎(chǔ)語法、關(guān)鍵參數(shù)、復(fù)雜對象排序、多條件排序、性能與穩(wěn)定性以及實戰(zhàn)應(yīng)用場景,通過這些內(nèi)容,讀者可以掌握如何高效地對各種可迭代對象進(jìn)行排序

sorted() 是 Python 中用于對可迭代對象進(jìn)行排序的內(nèi)置函數(shù),返回一個新的已排序列表,原對象保持不變。

本文將深入解析 sorted() 的用法、參數(shù)及實戰(zhàn)技巧,幫助你掌握各種排序場景。

一、基礎(chǔ)語法與核心功能

1. 基本語法

sorted(iterable, *, key=None, reverse=False)

參數(shù)

  • iterable:必需,可迭代對象(如列表、元組、集合、字典等)。
  • key:可選,指定排序依據(jù)的函數(shù)(如 len、str.lower)。
  • reverse:可選,布爾值,是否降序排序(默認(rèn) False 升序)。
  • 返回值:新的已排序列表。

2. 簡單示例

# 列表排序
numbers = [3, 1, 4, 1, 5, 9, 2]
sorted_numbers = sorted(numbers)
print(sorted_numbers)  # 輸出: [1, 1, 2, 3, 4, 5, 9]

# 元組排序(返回列表)
tuple_data = (5, 3, 1)
sorted_list = sorted(tuple_data)
print(sorted_list)  # 輸出: [1, 3, 5]

# 字符串排序(按字符編碼)
text = "python"
sorted_chars = sorted(text)
print(sorted_chars)  # 輸出: ['h', 'n', 'o', 'p', 't', 'y']

二、關(guān)鍵參數(shù)詳解

1.key參數(shù):自定義排序依據(jù)

  • key 接收一個函數(shù),該函數(shù)用于從每個元素中提取排序依據(jù)。
# 按字符串長度排序
words = ["apple", "banana", "cherry", "date"]
sorted_words = sorted(words, key=len)
print(sorted_words)  # 輸出: ['date', 'apple', 'cherry', 'banana']

# 按小寫字母排序
mixed_case = ["banana", "Apple", "Cherry"]
sorted_case_insensitive = sorted(mixed_case, key=str.lower)
print(sorted_case_insensitive)  # 輸出: ['Apple', 'banana', 'Cherry']

# 按元組的第二個元素排序
data = [(1, 5), (3, 1), (2, 8)]
sorted_data = sorted(data, key=lambda x: x[1])
print(sorted_data)  # 輸出: [(3, 1), (1, 5), (2, 8)]

2.reverse參數(shù):降序排序

  • reverse=True 表示降序排列。
numbers = [3, 1, 4, 1, 5, 9, 2]
descending = sorted(numbers, reverse=True)
print(descending)  # 輸出: [9, 5, 4, 3, 2, 1, 1]

三、復(fù)雜對象排序

1. 自定義類對象排序

  • 通過 key 指定排序依據(jù)的屬性或方法。
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def __repr__(self):
        return f"Person({self.name}, {self.age})"

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

# 按年齡排序
sorted_people = sorted(people, key=lambda p: p.age)
print(sorted_people)  # 輸出: [Person(Bob, 20), Person(Alice, 25), Person(Charlie, 30)]

2. 字典排序

  • 對字典排序時,默認(rèn)按鍵排序;如需按鍵值排序,需指定 key。
scores = {"Alice": 85, "Bob": 92, "Charlie": 78}

# 按鍵排序
sorted_keys = sorted(scores)
print(sorted_keys)  # 輸出: ['Alice', 'Bob', 'Charlie']

# 按值排序(返回鍵的列表)
sorted_by_value = sorted(scores, key=lambda k: scores[k])
print(sorted_by_value)  # 輸出: ['Charlie', 'Alice', 'Bob']

# 按值排序(返回元組列表)
sorted_items = sorted(scores.items(), key=lambda item: item[1])
print(sorted_items)  # 輸出: [('Charlie', 78), ('Alice', 85), ('Bob', 92)]

四、多條件排序

1. 多級排序

  • 通過返回元組實現(xiàn)多級排序(優(yōu)先級從左到右)。
students = [
    ("Alice", 25, 85),
    ("Bob", 20, 92),
    ("Charlie", 25, 78)
]  # 格式:(姓名, 年齡, 分?jǐn)?shù))

# 先按年齡升序,再按分?jǐn)?shù)降序
sorted_students = sorted(students, key=lambda s: (s[1], -s[2]))
print(sorted_students)  # 輸出: [('Bob', 20, 92), ('Charlie', 25, 78), ('Alice', 25, 85)]

2. 組合多個排序條件

  • 使用 functools.cmp_to_key 將比較函數(shù)轉(zhuǎn)換為 key 函數(shù)。
from functools import cmp_to_key

def custom_compare(a, b):
    # 先按長度降序,長度相同則按字母升序
    if len(a) != len(b):
        return len(b) - len(a)
    return (a > b) - (a < b)  # 字符串比較

words = ["apple", "banana", "cherry", "date", "elder"]
sorted_words = sorted(words, key=cmp_to_key(custom_compare))
print(sorted_words)  # 輸出: ['banana', 'cherry', 'elder', 'apple', 'date']

五、性能與穩(wěn)定性

1. 時間復(fù)雜度

  • sorted() 的時間復(fù)雜度為 O(n log n),其中 n 是元素數(shù)量。
  • 對于大規(guī)模數(shù)據(jù),可考慮使用 list.sort() 原地排序(性能略高)。

2. 穩(wěn)定性

  • Python 的排序算法是穩(wěn)定的,即相等元素的相對順序保持不變。
data = [(1, 'a'), (2, 'b'), (1, 'c')]
sorted_data = sorted(data, key=lambda x: x[0])
print(sorted_data)  # 輸出: [(1, 'a'), (1, 'c'), (2, 'b')]
# 原數(shù)據(jù)中 (1, 'a') 在 (1, 'c') 前,排序后保持此順序

六、實戰(zhàn)應(yīng)用場景

1. 數(shù)據(jù)篩選與排名

# 篩選前 N 個元素
numbers = [3, 1, 4, 1, 5, 9, 2]
top_three = sorted(numbers, reverse=True)[:3]
print(top_three)  # 輸出: [9, 5, 4]

# 按條件篩選并排序
people = [
    {"name": "Alice", "age": 25, "score": 85},
    {"name": "Bob", "age": 20, "score": 92},
    {"name": "Charlie", "age": 30, "score": 78}
]

adult_high_scores = sorted(
    [p for p in people if p["age"] >= 25],
    key=lambda p: p["score"],
    reverse=True
)
print(adult_high_scores)  # 輸出: [{'name': 'Alice', ...}, {'name': 'Charlie', ...}]

2. 自定義排序邏輯

# 特殊排序規(guī)則(負(fù)數(shù)排前,正數(shù)按絕對值排)
numbers = [5, -3, 2, -7, 1]
sorted_numbers = sorted(numbers, key=lambda x: (x < 0, abs(x)))
print(sorted_numbers)  # 輸出: [-3, -7, 1, 2, 5]

3. 處理非可比對象

# 對不可直接比較的對象排序
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    
    def distance_from_origin(self):
        return (self.x**2 + self.y**2) ** 0.5

points = [Point(3, 4), Point(0, 1), Point(1, 1)]
sorted_points = sorted(points, key=lambda p: p.distance_from_origin())
print([(p.x, p.y) for p in sorted_points])  # 輸出: [(0, 1), (1, 1), (3, 4)]

七、總結(jié)

sorted() 函數(shù)的核心要點:

基礎(chǔ)用法:對可迭代對象排序,返回新列表。

關(guān)鍵參數(shù)

  • key:自定義排序依據(jù),接收單參數(shù)函數(shù)。
  • reverse:控制升序 / 降序。

高級技巧

  • 通過返回元組實現(xiàn)多級排序。
  • 使用 cmp_to_key 處理復(fù)雜比較邏輯。

性能特點:時間復(fù)雜度 O (n log n),排序穩(wěn)定。

掌握 sorted() 能讓你高效處理各種排序需求,從簡單列表到復(fù)雜對象集合都能輕松應(yīng)對。合理使用 key 和 reverse 參數(shù)是實現(xiàn)靈活排序的關(guān)鍵。

總結(jié)

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論

辉南县| 卓尼县| 若尔盖县| 荣成市| 简阳市| 敦化市| 泌阳县| 屏东县| 隆昌县| 荃湾区| 西藏| 大厂| 桃园市| 齐齐哈尔市| 富民县| 滦平县| 荣昌县| 东乡族自治县| 育儿| 砚山县| 报价| 云霄县| 江西省| 潜山县| 丹寨县| 英吉沙县| 上高县| 盱眙县| 于田县| 大城县| 容城县| 永吉县| 布尔津县| 剑阁县| 将乐县| 玉龙| 宁城县| 高陵县| 剑阁县| 法库县| 蓬莱市|