<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>

                ThinkChat2.0新版上線,更智能更精彩,支持會話、畫圖、視頻、閱讀、搜索等,送10W Token,即刻開啟你的AI之旅 廣告
                ### 5. 數據結構 本章詳細講述你已經學過的一些知識,并增加一些新內容。 ### 5.1. 深入列表 列表數據類型還有更多的方法。這里是列表對象的所有方法: list.append(*x*) 添加一個元素到列表的末尾。相當于a[len(a):]=[x]。 list.extend(*L*) 將給定列表中的所有元素附加到另一個列表的末尾。相當于a[len(a):]=L。 list.insert(*i*, *x*) 在給定位置插入一個元素。第一個參數是準備插入到其前面的那個元素的索引,所以 a.insert(0,x) 在列表的最前面插入,a.insert(len(a),x) 相當于 a.append(x)。 list.remove(*x*) 刪除列表中第一個值為 *x* 的元素。如果沒有這樣的元素將會報錯。 list.pop([*i*]) 刪除列表中給定位置的元素并返回它。如果未指定索引,a.pop() 刪除并返回列表中的最后一個元素。(*i* 兩邊的方括號表示這個參數是可選的,而不是要你輸入方括號。你會在 Python 參考庫中經常看到這種表示法)。 list.clear() 刪除列表中所有的元素。相當于dela[:]。 list.index(*x*) 返回列表中第一個值為 *x* 的元素的索引。如果沒有這樣的元素將會報錯。 list.count(*x*) 返回列表中 *x* 出現的次數。 list.sort(*cmp=None*, *key=None*, *reverse=False*) 原地排序列表中的元素。 list.reverse() 原地反轉列表中的元素。 list.copy() 返回列表的一個淺拷貝。等同于a[:]。 使用了列表大多數方法的例子: ~~~ >>> a = [66.25, 333, 333, 1, 1234.5] >>> print(a.count(333), a.count(66.25), a.count('x')) 2 1 0 >>> a.insert(2, -1) >>> a.append(333) >>> a [66.25, 333, -1, 333, 1, 1234.5, 333] >>> a.index(333) 1 >>> a.remove(333) >>> a [66.25, -1, 333, 1, 1234.5, 333] >>> a.reverse() >>> a [333, 1234.5, 1, 333, -1, 66.25] >>> a.sort() >>> a [-1, 1, 66.25, 333, 333, 1234.5] >>> a.pop() 1234.5 >>> a [-1, 1, 66.25, 333, 333] ~~~ 你可能已經注意到像insert, remove 或者 sort之類的方法只修改列表而沒有返回值打印出來 -- 它們其實返回了默認值None。[[1]](#)這是 Python 中所有可變數據結構的設計原則。 #### 5.1.1. 將列表作為堆棧使用 列表方法使得將列表當作堆棧非常容易,最先進入的元素最后一個取出(后進先出)。使用 append() 將元素添加到堆棧的頂部。使用不帶索引的 pop() 從堆棧的頂部取出元素。例如: ~~~ >>> stack = [3, 4, 5] >>> stack.append(6) >>> stack.append(7) >>> stack [3, 4, 5, 6, 7] >>> stack.pop() 7 >>> stack [3, 4, 5, 6] >>> stack.pop() 6 >>> stack.pop() 5 >>> stack [3, 4] ~~~ #### 5.1.2. 將列表當作隊列使用 也可以將列表當作隊列使用,此時最先進入的元素第一個取出(先進先出);但是列表用作此目的效率不高。在列表的末尾添加和彈出元素非常快,但是在列表的開頭插入或彈出元素卻很慢 (因為所有的其他元素必須向后移一位)。 如果要實現一個隊列,可以使用 [collections.deque](# "collections.deque"),它設計的目的就是在兩端都能夠快速添加和彈出元素。例如: ~~~ >>> from collections import deque >>> queue = deque(["Eric", "John", "Michael"]) >>> queue.append("Terry") # Terry arrives >>> queue.append("Graham") # Graham arrives >>> queue.popleft() # The first to arrive now leaves 'Eric' >>> queue.popleft() # The second to arrive now leaves 'John' >>> queue # Remaining queue in order of arrival deque(['Michael', 'Terry', 'Graham']) ~~~ #### 5.1.3. 列表解析 列表解析提供了一個生成列表的簡潔方法。應用程序通常會從一個序列的每個元素的操作結果生成新的列表,或者生成滿足特定條件的元素的子序列。 例如,假設我們想要創建一個列表 squares: ~~~ >>> squares = [] >>> for x in range(10): ... squares.append(x**2) ... >>> squares [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] ~~~ 我們可以用下面的方式得到同樣的結果: ~~~ squares = [x**2 for x in range(10)] ~~~ 這也相當于squares=list(map(lambdax:x**2,range(10))),但是更簡潔和易讀。 列表解析由括號括起來,括號里面包含一個表達式,表達式后面跟著一個[for](#)語句,后面還可以接零個或更多的 ?[for](#) 或 [if](#) 語句。結果是一個新的列表,由表達式依據其后面的 [for](#) 和 [if](#) 字句上下文計算而來的結果構成。例如,下面的 listcomp 組合兩個列表中不相等的元素: ~~~ >>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y] [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)] ~~~ 它等效于: ~~~ >>> combs = [] >>> for x in [1,2,3]: ... for y in [3,1,4]: ... if x != y: ... combs.append((x, y)) ... >>> combs [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)] ~~~ 注意在兩個代碼段中[for](#) 和 [if](#) 語句的順序是相同的。 如果表達式是一個元組(例如前面示例中的 (x,y)),它必須帶圓括號。 ~~~ >>> vec = [-4, -2, 0, 2, 4] >>> # create a new list with the values doubled >>> [x*2 for x in vec] [-8, -4, 0, 4, 8] >>> # filter the list to exclude negative numbers >>> [x for x in vec if x >= 0] [0, 2, 4] >>> # apply a function to all the elements >>> [abs(x) for x in vec] [4, 2, 0, 2, 4] >>> # call a method on each element >>> freshfruit = [' banana', ' loganberry ', 'passion fruit '] >>> [weapon.strip() for weapon in freshfruit] ['banana', 'loganberry', 'passion fruit'] >>> # create a list of 2-tuples like (number, square) >>> [(x, x**2) for x in range(6)] [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)] >>> # the tuple must be parenthesized, otherwise an error is raised >>> [x, x**2 for x in range(6)] File "<stdin>", line 1, in ? [x, x**2 for x in range(6)] ^ SyntaxError: invalid syntax >>> # flatten a list using a listcomp with two 'for' >>> vec = [[1,2,3], [4,5,6], [7,8,9]] >>> [num for elem in vec for num in elem] [1, 2, 3, 4, 5, 6, 7, 8, 9] ~~~ 列表解析可以包含復雜的表達式和嵌套的函數: ~~~ >>> from math import pi >>> [str(round(pi, i)) for i in range(1, 6)] ['3.1', '3.14', '3.142', '3.1416', '3.14159'] ~~~ #### 5.1.4. 嵌套的列表解析 列表解析中的第一個表達式可以是任何表達式,包括列表解析。 考慮下面由三個長度為 4 的列表組成的 3x4 矩陣: ~~~ >>> matrix = [ ... [1, 2, 3, 4], ... [5, 6, 7, 8], ... [9, 10, 11, 12], ... ] ~~~ 下面的列表解析將轉置行和列: ~~~ >>> [[row[i] for row in matrix] for i in range(4)] [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]] ~~~ 正如我們在上一節中看到的,嵌套的 listcomp 在跟隨它之后的[for](#) 字句中計算,所以此例等同于: ~~~ >>> transposed = [] >>> for i in range(4): ... transposed.append([row[i] for row in matrix]) ... >>> transposed [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]] ~~~ 以此下去,還等同于: ~~~ >>> transposed = [] >>> for i in range(4): ... # the following 3 lines implement the nested listcomp ... transposed_row = [] ... for row in matrix: ... transposed_row.append(row[i]) ... transposed.append(transposed_row) ... >>> transposed [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]] ~~~ 在實際中,與復雜的控制流比起來,你應該更喜歡內置的函數。針對這種場景,使用 [zip()](# "zip") 函數會更好: ~~~ >>> list(zip(*matrix)) [(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)] ~~~ 關于本行中使用的星號的說明,請參閱[*參數列表的分拆*](#)。 ### 5.2. [del](#)語句 有個方法可以從列表中按索引而不是值來刪除一個元素: [del](#) 語句。這不同于有返回值的 pop() 方法。[del](#) 語句還可以用于從列表中刪除切片或清除整個列表 (我們是將空列表賦值給切片)。例如: ~~~ >>> a = [-1, 1, 66.25, 333, 333, 1234.5] >>> del a[0] >>> a [1, 66.25, 333, 333, 1234.5] >>> del a[2:4] >>> a [1, 66.25, 1234.5] >>> del a[:] >>> a [] ~~~ [del](#) 也可以用于刪除整個變量: ~~~ >>> del a ~~~ 此后再引用名稱 a 將會報錯(直到有另一個值被賦給它)。稍后我們將看到 [del](#) 的其它用途 。 ### 5.3. 元組和序列 我們已經看到列表和字符串具有很多共同的屬性,如索引和切片操作。它們是 *序列* 數據類型的兩個例子(參見 [*Sequence Types — list, tuple, range*](#))。因為 Python 是一個正在不斷進化的語言,其他的序列類型也可能被添加進來。還有另一種標準序列數據類型:*元組*。 元組由逗號分割的若干值組成,例如: ~~~ >>> t = 12345, 54321, 'hello!' >>> t[0] 12345 >>> t (12345, 54321, 'hello!') >>> # Tuples may be nested: ... u = t, (1, 2, 3, 4, 5) >>> u ((12345, 54321, 'hello!'), (1, 2, 3, 4, 5)) >>> # Tuples are immutable: ... t[0] = 88888 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'tuple' object does not support item assignment >>> # but they can contain mutable objects: ... v = ([1, 2, 3], [3, 2, 1]) >>> v ([1, 2, 3], [3, 2, 1]) ~~~ 如你所見,元組在輸出時總是有括號的,以便于正確表達嵌套結構;在輸入時括號可有可無,不過括號經常都是必須的(如果元組是一個更大的表達式的一部分)。不能給元組中單獨的一個元素賦值,不過可以創建包含可變對象(例如列表)的元組。 雖然元組看起來類似于列表,它們經常用于不同的場景和不同的目的。元組是[*不可變的*](#),通常包含不同種類的元素并通過分拆(參閱本節后面的內容) 或索引訪問(如果是[namedtuples](# "collections.namedtuple"),甚至可以通過屬性)。列表是 [*可變*](#) 的,它們的元素通常是相同類型的并通過迭代訪問。 一個特殊的情況是構造包含 0 個或 1 個元素的元組:為了實現這種情況,語法上有一些奇怪。空元組由一對空括號創建;只有一個元素的元組由值后面跟隨一個逗號創建 (在括號中放入單獨一個值還不夠)。丑陋,但是有效。例如: ~~~ >>> empty = () >>> singleton = 'hello', # <-- note trailing comma >>> len(empty) 0 >>> len(singleton) 1 >>> singleton ('hello',) ~~~ 語句t=12345,54321,'hello!' 是一個*元組封裝*的例子: 值12345,54321 和 'hello!' 被一起放入一個元組。其逆操作也是可以的: ~~~ >>> x, y, z = t ~~~ 這被稱為 *序列分拆* 再恰當不過了,且可以用于右邊的任何序列。序列分拆要求等號左側的變量和序列中的元素的數目相同。注意多重賦值只是同時進行元組封裝和序列分拆。 ### 5.4. 集合 Python 還包含了一個數據類型 *集合*。集合中的元素不會重復且沒有順序。集合的基本用途有成員測試和消除重復的條目。集合對象還支持并集、 交集、 差和對稱差等數學運算。 花大括號或 [set()](# "set") 函數可以用于創建集合。注意: 若要創建一個空集必須使用set(),而不能用 {};后者將創建一個空的字典,一個我們在下一節中討論數據結構。 這里是一個簡短的演示: ~~~ >>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'} >>> print(basket) # show that duplicates have been removed {'orange', 'banana', 'pear', 'apple'} >>> 'orange' in basket # fast membership testing True >>> 'crabgrass' in basket False >>> # Demonstrate set operations on unique letters from two words ... >>> a = set('abracadabra') >>> b = set('alacazam') >>> a # unique letters in a {'a', 'r', 'b', 'c', 'd'} >>> a - b # letters in a but not in b {'r', 'd', 'b'} >>> a | b # letters in either a or b {'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'} >>> a & b # letters in both a and b {'a', 'c'} >>> a ^ b # letters in a or b but not both {'r', 'd', 'b', 'm', 'z', 'l'} ~~~ 和 [*列表解析*](#) 類似,Python 也支持集合解析: ~~~ >>> a = {x for x in 'abracadabra' if x not in 'abc'} >>> a {'r', 'd'} ~~~ ### 5.5. 字典 Python 中內置的另一種有用的數據類型是*字典*(見[*映射的類型 —— 字典*](#))。有時候你會發現字典在其它語言中被稱為?“associative memories” 或者 “associative arrays”。與序列不同,序列由數字做索引,字典由 *鍵* 做索引,鍵可以是任意不可變類型;字符串和數字永遠可以拿來做鍵。如果元組只包含字符串、 數字或元組,它們可以用作鍵;如果元組直接或間接地包含任何可變對象,不能用作鍵。不能用列表作為鍵,因為列表可以用索引、切片或者 append() 和extend() 方法修改。 理解字典的最佳方式是把它看做無序的 *鍵:值* ?對集合,要求是鍵必須是唯一的(在同一個字典內)。一對大括號將創建一個空的字典: {}。大括號中由逗號分隔的 鍵:值 對將成為字典的初始值;打印字典時也是按照這種方式輸出。 字典的主要操作是依據鍵來存取值。也可以通過 del 刪除 鍵: 值 對。如果用一個已經存在的鍵存儲值,以前為該關鍵字分配的值就會被遺忘。用一個不存在的鍵中讀取值會導致錯誤。 list(d.keys())返回字典中所有鍵組成的列表,列表的順序是隨機的(如果你想它是有序的,只需使用sorted(d.keys())代替)。[[2]](#)要檢查某個鍵是否在字典中,可以使用 [in](#) 關鍵字。 下面是一個使用字典的小示例: ~~~ >>> tel = {'jack': 4098, 'sape': 4139} >>> tel['guido'] = 4127 >>> tel {'sape': 4139, 'guido': 4127, 'jack': 4098} >>> tel['jack'] 4098 >>> del tel['sape'] >>> tel['irv'] = 4127 >>> tel {'guido': 4127, 'irv': 4127, 'jack': 4098} >>> list(tel.keys()) ['irv', 'guido', 'jack'] >>> sorted(tel.keys()) ['guido', 'irv', 'jack'] >>> 'guido' in tel True >>> 'jack' not in tel False ~~~ [dict()](# "dict") 構造函數直接從鍵-值對序列創建字典: ~~~ >>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)]) {'sape': 4139, 'jack': 4098, 'guido': 4127} ~~~ 此外,字典解析可以用于從任意鍵和值表達式創建字典: ~~~ >>> {x: x**2 for x in (2, 4, 6)} {2: 4, 4: 16, 6: 36} ~~~ 如果鍵都是簡單的字符串,有時通過關鍵字參數指定 鍵-值 對更為方便: ~~~ >>> dict(sape=4139, guido=4127, jack=4098) {'sape': 4139, 'jack': 4098, 'guido': 4127} ~~~ ### 5.6. 遍歷的技巧 循環迭代字典的時候,鍵和對應的值通過使用items()方法可以同時得到。 ~~~ >>> knights = {'gallahad': 'the pure', 'robin': 'the brave'} >>> for k, v in knights.items(): ... print(k, v) ... gallahad the pure robin the brave ~~~ 序列中遍歷時,使用 [enumerate()](# "enumerate") 函數可以同時得到索引和對應的值。 ~~~ >>> for i, v in enumerate(['tic', 'tac', 'toe']): ... print(i, v) ... 0 tic 1 tac 2 toe ~~~ 同時遍歷兩個或更多的序列,使用 [zip()](# "zip") 函數可以成對讀取元素。 ~~~ >>> questions = ['name', 'quest', 'favorite color'] >>> answers = ['lancelot', 'the holy grail', 'blue'] >>> for q, a in zip(questions, answers): ... print('What is your {0}? It is {1}.'.format(q, a)) ... What is your name? It is lancelot. What is your quest? It is the holy grail. What is your favorite color? It is blue. ~~~ 要反向遍歷一個序列,首先正向生成這個序列,然后調用 [reversed()](# "reversed") 函數。 ~~~ >>> for i in reversed(range(1, 10, 2)): ... print(i) ... 9 7 5 3 1 ~~~ 循環一個序列按排序順序,請使用[sorted()](# "sorted")函數,返回一個新的排序的列表,同時保留源不變。 ~~~ >>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'] >>> for f in sorted(set(basket)): ... print(f) ... apple banana orange pear ~~~ 若要在循環內部修改正在遍歷的序列(例如復制某些元素),建議您首先制作副本。在序列上循環不會隱式地創建副本。切片表示法使這尤其方便: ~~~ >>> words = ['cat', 'window', 'defenestrate'] >>> for w in words[:]: # Loop over a slice copy of the entire list. ... if len(w) > 6: ... words.insert(0, w) ... >>> words ['defenestrate', 'cat', 'window', 'defenestrate'] ~~~ ### 5.7. 深入條件控制 while 和 if 語句中使用的條件可以包含任意的操作,而不僅僅是比較。 比較操作符 in 和 notin 檢查一個值是否在一個序列中出現(不出現)。is 和 isnot 比較兩個對象是否為同一對象;這只和列表這樣的可變對象有關。所有比較運算符都具有相同的優先級,低于所有數值運算符。 可以級聯比較。例如, a<b= =c 測試 a 是否小于 b 并且 b 等于 c。 可將布爾運算符 and 和 or 用于比較,比較的結果(或任何其他的布爾表達式)可以用 not 取反。這些操作符的優先級又低于比較操作符;它們之間,not 優先級最高,or 優先級最低,所以 Aand notBorC 等效于 (Aand(notB))orC。與往常一樣,可以使用括號來表示所需的組合。 布爾運算符and 和 or 是所謂的 *短路* 運算符:依參數從左向右求值,結果一旦確定就停止。例如,如果A 和 C 都為真,但B是假, AandBandC 將不計算表達式 C。用作一個普通值而非邏輯值時,短路操作符的返回值通常是最后一個計算的。 可以把比較或其它邏輯表達式的返回值賦給一個變量。例如, ~~~ >>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance' >>> non_null = string1 or string2 or string3 >>> non_null 'Trondheim' ~~~ 注意 Python 與 C 不同,在表達式內部不能賦值。C 程序員可能會抱怨這一點,但它避免了一類 C 程序中常見的問題: 在表達式中輸入 = 而真正的意圖是== 。 ### 5.8. 序列和其它類型的比較 序列對象可以與具有相同序列類型的其他對象相比較。比較按照 *字典序* 進行: 首先比較最前面的兩個元素,如果不同,就決定了比較的結果;如果相同,就比較后面兩個元素,依此類推,直到其中一個序列窮舉完。如果要比較的兩個元素本身就是同一類型的序列,就按字典序遞歸比較。如果兩個序列的所有元素都相等,就為序認列相等。如果一個序列是另一個序列的初始子序列,較短的序列就小于另一個。字符串的排序按照Unicode編碼點的數值排序單個字符。下面是同類型序列之間比較的一些例子: ~~~ (1, 2, 3) < (1, 2, 4) [1, 2, 3] < [1, 2, 4] 'ABC' < 'C' < 'Pascal' < 'Python' (1, 2, 3, 4) < (1, 2, 4) (1, 2) < (1, 2, -1) (1, 2, 3) == (1.0, 2.0, 3.0) (1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4) ~~~ 注意,使用< 或者 >比較不同類型的對象是合法的,只要這些對象具有合適的比較方法。例如,不同的數字類型按照它們的數值比較,所以 0 等于 0.0,等等。否則,解釋器將引發一個[TypeError](# "TypeError")異常,而不是隨便給一個順序。 腳注 | [[1]](#) | Other languages may return the mutated object, which allows method chaining, such as d->insert("a")->remove("b")->sort();. | |-----|-----| | [[2]](#) | Calling d.keys() will return a *dictionary view* object. It supports operations like membership test and iteration, but its contents are not independent of the original dictionary – it is only a *view*. | |-----|-----|
                  <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>

                              哎呀哎呀视频在线观看