<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                企業??AI智能體構建引擎,智能編排和調試,一鍵部署,支持知識庫和私有化部署方案 廣告
                ### 導航 - [索引](../genindex.xhtml "總目錄") - [模塊](../py-modindex.xhtml "Python 模塊索引") | - [下一頁](unicode.xhtml "Unicode 指南") | - [上一頁](sockets.xhtml "套接字編程指南") | - ![](https://box.kancloud.cn/a721fc7ec672275e257bbbfde49a4d4e_16x16.png) - [Python](https://www.python.org/) ? - zh\_CN 3.7.3 [文檔](../index.xhtml) ? - [Python 常用指引](index.xhtml) ? - $('.inline-search').show(0); | # 排序指南 作者Andrew Dalke 和 Raymond Hettinger 發布版本0\.1 Python 列表有一個內置的 [`list.sort()`](../library/stdtypes.xhtml#list.sort "list.sort") 方法可以直接修改列表。還有一個 [`sorted()`](../library/functions.xhtml#sorted "sorted") 內置函數,它會從一個可迭代對象構建一個新的排序列表。 在本文檔中,我們將探索使用Python對數據進行排序的各種技術。 ## 基本排序 簡單的升序排序非常簡單:只需調用 [`sorted()`](../library/functions.xhtml#sorted "sorted") 函數即可。它會返回一個新的已排序列表。 ``` >>> sorted([5, 2, 3, 1, 4]) [1, 2, 3, 4, 5] ``` 你也可以使用 [`list.sort()`](../library/stdtypes.xhtml#list.sort "list.sort") 方法,它會直接修改原列表(并返回 `None` 以避免混淆),通常來說它不如 [`sorted()`](../library/functions.xhtml#sorted "sorted") 方便 ——— 但如果你不需要原列表,它會更有效率。 ``` >>> a = [5, 2, 3, 1, 4] >>> a.sort() >>> a [1, 2, 3, 4, 5] ``` 另外一個區別是, [`list.sort()`](../library/stdtypes.xhtml#list.sort "list.sort") 方法只是為列表定義的,而 [`sorted()`](../library/functions.xhtml#sorted "sorted") 函數可以接受任何可迭代對象。 ``` >>> sorted({1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'}) [1, 2, 3, 4, 5] ``` ## 關鍵函數 [`list.sort()`](../library/stdtypes.xhtml#list.sort "list.sort") 和 [`sorted()`](../library/functions.xhtml#sorted "sorted") 都有一個 *key* 形參來指定在進行比較之前要在每個列表元素上進行調用的函數。 例如,下面是一個不區分大小寫的字符串比較: ``` >>> sorted("This is a test string from Andrew".split(), key=str.lower) ['a', 'Andrew', 'from', 'is', 'string', 'test', 'This'] ``` *key* 形參的值應該是一個函數,它接受一個參數并并返回一個用于排序的鍵。這種技巧速度很快,因為對于每個輸入記錄只會調用一次 key 函數。 一種常見的模式是使用對象的一些索引作為鍵對復雜對象進行排序。例如: ``` >>> student_tuples = [ ... ('john', 'A', 15), ... ('jane', 'B', 12), ... ('dave', 'B', 10), ... ] >>> sorted(student_tuples, key=lambda student: student[2]) # sort by age [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)] ``` 同樣的技術也適用于具有命名屬性的對象。例如: ``` >>> class Student: ... def __init__(self, name, grade, age): ... self.name = name ... self.grade = grade ... self.age = age ... def __repr__(self): ... return repr((self.name, self.grade, self.age)) ``` ``` >>> student_objects = [ ... Student('john', 'A', 15), ... Student('jane', 'B', 12), ... Student('dave', 'B', 10), ... ] >>> sorted(student_objects, key=lambda student: student.age) # sort by age [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)] ``` ## Operator 模塊函數 上面顯示的鍵函數模式非常常見,因此 Python 提供了便利功能,使訪問器功能更容易,更快捷。 [`operator`](../library/operator.xhtml#module-operator "operator: Functions corresponding to the standard operators.") 模塊有 [`itemgetter()`](../library/operator.xhtml#operator.itemgetter "operator.itemgetter") 、 [`attrgetter()`](../library/operator.xhtml#operator.attrgetter "operator.attrgetter") 和 [`methodcaller()`](../library/operator.xhtml#operator.methodcaller "operator.methodcaller") 函數。 使用這些函數,上述示例變得更簡單,更快捷: ``` >>> from operator import itemgetter, attrgetter ``` ``` >>> sorted(student_tuples, key=itemgetter(2)) [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)] ``` ``` >>> sorted(student_objects, key=attrgetter('age')) [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)] ``` Operator 模塊功能允許多級排序。 例如,按 *grade* 排序,然后按 *age* 排序: ``` >>> sorted(student_tuples, key=itemgetter(1,2)) [('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)] ``` ``` >>> sorted(student_objects, key=attrgetter('grade', 'age')) [('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)] ``` ## 升序和降序 [`list.sort()`](../library/stdtypes.xhtml#list.sort "list.sort") 和 [`sorted()`](../library/functions.xhtml#sorted "sorted") 接受布爾值的 *reverse* 參數。這用于標記降序排序。 例如,要以反向 *age* 順序獲取學生數據: ``` >>> sorted(student_tuples, key=itemgetter(2), reverse=True) [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)] ``` ``` >>> sorted(student_objects, key=attrgetter('age'), reverse=True) [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)] ``` ## 排序穩定性和排序復雜度 排序保證是 [穩定](https://en.wikipedia.org/wiki/Sorting_algorithm#Stability) \[https://en.wikipedia.org/wiki/Sorting\_algorithm#Stability\] 的。 這意味著當多個記錄具有相同的鍵值時,將保留其原始順序。 ``` >>> data = [('red', 1), ('blue', 1), ('red', 2), ('blue', 2)] >>> sorted(data, key=itemgetter(0)) [('blue', 1), ('blue', 2), ('red', 1), ('red', 2)] ``` 注意 *blue* 的兩個記錄如何保留它們的原始順序,以便 `('blue', 1)` 保證在 `('blue', 2)` 之前。 這個美妙的屬性允許你在一系列排序步驟中構建復雜的排序。例如,要按 *grade* 降序然后 *age* 升序對學生數據進行排序,請先 *age* 排序,然后再使用 *grade* 排序: ``` >>> s = sorted(student_objects, key=attrgetter('age')) # sort on secondary key >>> sorted(s, key=attrgetter('grade'), reverse=True) # now sort on primary key, descending [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)] ``` Python 中使用的 [Timsort](https://en.wikipedia.org/wiki/Timsort) \[https://en.wikipedia.org/wiki/Timsort\] 算法可以有效地進行多種排序,因為它可以利用數據集中已存在的任何排序。 ## 使用裝飾-排序-去裝飾的舊方法 這個三個步驟被稱為 Decorate-Sort-Undecorate : - 首先,初始列表使用控制排序順序的新值進行修飾。 - 然后,裝飾列表已排序。 - 最后,刪除裝飾,創建一個僅包含新排序中初始值的列表。 例如,要使用DSU方法按 *grade* 對學生數據進行排序: ``` >>> decorated = [(student.grade, i, student) for i, student in enumerate(student_objects)] >>> decorated.sort() >>> [student for grade, i, student in decorated] # undecorate [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)] ``` 這方法語有效是因為元組按字典順序進行比較,先比較第一項;如果它們相同則比較第二個項目,依此類推。 不一定在所有情況下都要在裝飾列表中包含索引 *i* ,但包含它有兩個好處: - 排序是穩定的——如果兩個項具有相同的鍵,它們的順序將保留在排序列表中。 - 原始項目不必具有可比性,因為裝飾元組的排序最多由前兩項決定。 因此,例如原始列表可能包含無法直接排序的復數。 這個方法的另一個名字是 Randal L. Schwartz 在 Perl 程序員中推廣的 [Schwartzian transform](https://en.wikipedia.org/wiki/Schwartzian_transform) \[https://en.wikipedia.org/wiki/Schwartzian\_transform\]。 既然 Python 排序提供了鍵函數,那么通常不需要這種技術。 ## 使用 *cmp* 參數的舊方法 本 HOWTO 中給出的許多結構都假定為 Python 2.4 或更高版本。在此之前,沒有內置 [`sorted()`](../library/functions.xhtml#sorted "sorted") , [`list.sort()`](../library/stdtypes.xhtml#list.sort "list.sort") 也沒有關鍵字參數。相反,所有 Py2.x 版本都支持 *cmp* 參數來處理用戶指定的比較函數。 在 Py3.0 中, *cmp* 參數被完全刪除(作為簡化和統一語言努力的一部分,消除了豐富的比較與 `__cmp__()` 魔術方法之間的沖突)。 在 Py2.x 中, sort 允許一個可選函數,可以調用它來進行比較。該函數應該采用兩個參數進行比較,然后返回負值為小于,如果它們相等則返回零,或者返回大于大于的正值。例如,我們可以這樣做: ``` >>> def numeric_compare(x, y): ... return x - y >>> sorted([5, 2, 4, 1, 3], cmp=numeric_compare) # doctest: +SKIP [1, 2, 3, 4, 5] ``` 或者你可反轉比較的順序: ``` >>> def reverse_numeric(x, y): ... return y - x >>> sorted([5, 2, 4, 1, 3], cmp=reverse_numeric) # doctest: +SKIP [5, 4, 3, 2, 1] ``` 將代碼從 Python 2.x 移植到 3.x 時,如果用戶提供比較功能并且需要將其轉換為鍵函數,則會出現這種情況。 以下包裝器使這很容易: ``` def cmp_to_key(mycmp): 'Convert a cmp= function into a key= function' class K: def __init__(self, obj, *args): self.obj = obj def __lt__(self, other): return mycmp(self.obj, other.obj) < 0 def __gt__(self, other): return mycmp(self.obj, other.obj) > 0 def __eq__(self, other): return mycmp(self.obj, other.obj) == 0 def __le__(self, other): return mycmp(self.obj, other.obj) <= 0 def __ge__(self, other): return mycmp(self.obj, other.obj) >= 0 def __ne__(self, other): return mycmp(self.obj, other.obj) != 0 return K ``` 要轉換為鍵函數,只需包裝舊的比較函數: ``` >>> sorted([5, 2, 4, 1, 3], key=cmp_to_key(reverse_numeric)) [5, 4, 3, 2, 1] ``` 在 Python 3.2 中, [`functools.cmp_to_key()`](../library/functools.xhtml#functools.cmp_to_key "functools.cmp_to_key") 函數被添加到標準庫中的 [`functools`](../library/functools.xhtml#module-functools "functools: Higher-order functions and operations on callable objects.") 模塊中。 ## 其它 - 對于區域相關的排序,請使用 [`locale.strxfrm()`](../library/locale.xhtml#locale.strxfrm "locale.strxfrm") 作為鍵函數,或者 [`locale.strcoll()`](../library/locale.xhtml#locale.strcoll "locale.strcoll") 作為比較函數。 - *reverse* 參數仍然保持排序穩定性(因此具有相等鍵的記錄保留原始順序)。 有趣的是,通過使用內置的 [`reversed()`](../library/functions.xhtml#reversed "reversed") 函數兩次,可以在沒有參數的情況下模擬該效果: ``` >>> data = [('red', 1), ('blue', 1), ('red', 2), ('blue', 2)] >>> standard_way = sorted(data, key=itemgetter(0), reverse=True) >>> double_reversed = list(reversed(sorted(reversed(data), key=itemgetter(0)))) >>> assert standard_way == double_reversed >>> standard_way [('red', 1), ('red', 2), ('blue', 1), ('blue', 2)] ``` - 在兩個對象之間進行比較時,保證排序例程使用 [`__lt__()`](../reference/datamodel.xhtml#object.__lt__ "object.__lt__") 。 因此,通過定義 [`__lt__()`](../reference/datamodel.xhtml#object.__lt__ "object.__lt__") 方法,可以很容易地為類添加標準排序順序: ``` >>> Student.__lt__ = lambda self, other: self.age < other.age >>> sorted(student_objects) [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)] ``` - 鍵函數不需要直接依賴于被排序的對象。鍵函數還可以訪問外部資源。例如,如果學生成績存儲在字典中,則可以使用它們對單獨的學生姓名列表進行排序: ``` >>> students = ['dave', 'john', 'jane'] >>> newgrades = {'john': 'F', 'jane':'A', 'dave': 'C'} >>> sorted(students, key=newgrades.__getitem__) ['jane', 'dave', 'john'] ``` ### 導航 - [索引](../genindex.xhtml "總目錄") - [模塊](../py-modindex.xhtml "Python 模塊索引") | - [下一頁](unicode.xhtml "Unicode 指南") | - [上一頁](sockets.xhtml "套接字編程指南") | - ![](https://box.kancloud.cn/a721fc7ec672275e257bbbfde49a4d4e_16x16.png) - [Python](https://www.python.org/) ? - zh\_CN 3.7.3 [文檔](../index.xhtml) ? - [Python 常用指引](index.xhtml) ? - $('.inline-search').show(0); | ? [版權所有](../copyright.xhtml) 2001-2019, Python Software Foundation. Python 軟件基金會是一個非盈利組織。 [請捐助。](https://www.python.org/psf/donations/) 最后更新于 5月 21, 2019. [發現了問題](../bugs.xhtml)? 使用[Sphinx](http://sphinx.pocoo.org/)1.8.4 創建。
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看