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

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

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

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

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

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

1. 基本語(yǔ)法

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

參數(shù)

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

2. 簡(jiǎn)單示例

# 列表排序
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 接收一個(gè)函數(shù),該函數(shù)用于從每個(gè)元素中提取排序依據(jù)。
# 按字符串長(zhǎng)度排序
words = ["apple", "banana", "cherry", "date"]
sorted_words = sorted(words, key=len)
print(sorted_words)  # 輸出: ['date', 'apple', 'cherry', 'banana']

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

# 按元組的第二個(gè)元素排序
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ù)雜對(duì)象排序

1. 自定義類(lèi)對(duì)象排序

  • 通過(guò) 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. 字典排序

  • 對(duì)字典排序時(shí),默認(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. 多級(jí)排序

  • 通過(guò)返回元組實(shí)現(xiàn)多級(jí)排序(優(yōu)先級(jí)從左到右)。
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. 組合多個(gè)排序條件

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

def custom_compare(a, b):
    # 先按長(zhǎng)度降序,長(zhǎng)度相同則按字母升序
    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. 時(shí)間復(fù)雜度

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

2. 穩(wěn)定性

  • Python 的排序算法是穩(wěn)定的,即相等元素的相對(duì)順序保持不變。
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') 前,排序后保持此順序

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

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

# 篩選前 N 個(gè)元素
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ù)按絕對(duì)值排)
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. 處理非可比對(duì)象

# 對(duì)不可直接比較的對(duì)象排序
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ù)的核心要點(diǎn):

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

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

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

高級(jí)技巧

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

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

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

總結(jié)

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

相關(guān)文章

最新評(píng)論

公安县| 潮安县| 扎鲁特旗| 昌宁县| 宾阳县| 泸水县| 云霄县| 峨眉山市| 林芝县| 奎屯市| 浙江省| 通许县| 北碚区| 邵东县| 晋江市| 义马市| 寿光市| 青州市| 麻阳| 合阳县| 瑞安市| 墨江| 武山县| 惠东县| 历史| 比如县| 台安县| 南郑县| 交口县| 噶尔县| 富川| 临泉县| 海原县| 广丰县| 子洲县| 白山市| 确山县| 阜新| 清丰县| 英山县| 蓝山县|