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

                ??碼云GVP開源項目 12k star Uniapp+ElementUI 功能強大 支持多語言、二開方便! 廣告
                # Chapter 12 Tuples 元組 This chapter presents one more built-in type, the tuple, and then shows how lists, dictionaries, and tuples work together. I also present a useful feature for variable-length argument lists, the gather and scatter operators. > 本章我們要說的是另外一種內置類型,元組,以及列表、字典和元組如何協同工作。此外還有一個非常有用的功能:可變長度的列表,聚集和分散運算符。 One note: there is no consensus on how to pronounce “tuple”. Some people say “tuh-ple”, which rhymes with “supple”. But in the context of programming, most people say “too-ple”, which rhymes with “quadruple”. > 一點提示:元組的英文單詞 tuple 怎么讀還有爭議。有人認為是發[t?p?l] 的音,就跟『supple』里面的一樣讀音。但編程語境下,大家普遍讀[tu:p?l],跟『quadruple』里一樣。 ## 12.1 Tuples are immutable 元組不可修改 A tuple is a sequence of values. The values can be any type, and they are indexed by integers, so in that respect tuples are a lot like lists. The important difference is that tuples are immutable. Syntactically, a tuple is a comma-separated list of values: > 元組是一系列的值。這些值可以是任意類型的,并且用整數序號作為索引,所以可以發現元組和列表非常相似。二者間重要的區別就是元組是不可修改的。 > 元組的語法是一系列用逗號分隔的值: ```Python >>> t = 'a', 'b', 'c', 'd', 'e' >>> t = 'a', 'b', 'c', 'd', 'e' ``` Although it is not necessary, it is common to enclose tuples in parentheses: > 通常都用一對圓括號把元組的元素包括起來,當然不這樣也沒事。 ```Python >>> t = ('a', 'b', 'c', 'd', 'e') >>> t = ('a', 'b', 'c', 'd', 'e') ``` To create a tuple with a single element, you have to include a final comma: > 要建立一個單個元素構成的元組,必須要在結尾加上逗號: ```Python >>> t1 = 'a', >>> t1 = 'a', >>> type(t1) >>> type(t1) <class 'tuple'> ``` A value in parentheses is not a tuple: > 只用括號放一個值則并不是元組: ```Python >>> t2 = ('a') >>> t2 = ('a') >>> type(t2) >>> type(t2) <class 'str'> ``` Another way to create a tuple is the built-in function tuple. With no argument, it creates an empty tuple: > 另一中建立元組的方法是使用內置函數 tuple。不提供參數的情況下,默認就建立一個空的元組。 ```Python >>> t = tuple() >>> t = tuple() >>> t >>> t () ``` If the argument is a sequence (string, list or tuple), the result is a tuple with the elements of the sequence: > 如果參數為一個序列(比如字符串、列表或者元組),結果就會得到一個以該序列元素組成的元組。 ```Python >>> t = tuple('lupins') >>> t = tuple('lupins') >>> t >>> t ('l', 'u', 'p', 'i', 'n', 's') ``` Because tuple is the name of a built-in function, you should avoid using it as a variable name. Most list operators also work on tuples. The bracket operator indexes an element: > tuple 是內置函數命了,所以你就不能用來作為變量名了。 > 列表的各種運算符也基本適用于元組。方括號可以用來索引元素: ```Python >>> t = ('a', 'b', 'c', 'd', 'e') >>> t = ('a', 'b', 'c', 'd', 'e') >>> t[0] >>> t[0] 'a' ``` And the slice operator selects a range of elements. > 切片運算符也可以用于選取某一區間的元素。 ```Python >>> t[1:3] >>> t[1:3] ('b', 'c') ``` But if you try to modify one of the elements of the tuple, you get an error: > 但如果你想修改元組中的某個元素,就會得到錯誤了: ```Python >>> t[0] = 'A' >>> t[0] = 'A' TypeError: object doesn't support item assignment ``` Because tuples are immutable, you can’t modify the elements. But you can replace one tuple with another: > 因為元組是不能修改的,你不能修改其中的元素。但是可以用另一個元組來替換已有的元組。 ```Python >>> t = ('A',) + t[1:] >>> t = ('A',) + t[1:] >>> t >>> t ('A', 'b', 'c', 'd', 'e') ``` This statement makes a new tuple and then makes t refer to it. The relational operators work with tuples and other sequences; Python starts by comparing the first element from each sequence. If they are equal, it goes on to the next elements, and so on, until it finds elements that differ. Subsequent elements are not considered (even if they are really big). > 上面這個語句建立了一個新的元組,然后讓 t 指向了這個新的元組。 > 關系運算符也適用于元組和其他序列;Python 從每個元素的首個元素開始對比。如果相等,就對比下一個元素,依此類推,之道找到不同元素為止。 > 有了不同元素之后,后面的其他元素就被忽略掉了(即便很大也沒用)。 ```Python >>> (0, 1, 2) < (0, 3, 4) >>> (0, 1, 2) < (0, 3, 4) True >>> (0, 1, 2000000) < (0, 3, 4) >>> (0, 1, 2000000) < (0, 3, 4) True ``` ## 12.2 Tuple assignment 元組賦值 It is often useful to swap the values of two variables. With conventional assignments, you have to use a temporary variable. For example, to swap a and b: > 對兩個變量的值進行交換是一種常用操作。用常見語句來實現的話,就必須有一個臨時變量。比如下面這個例子中是交換 a 和 b: ```Python >>> temp = a >>> temp = a >>> a = b >>> a = b >>> b = temp >>> b = temp ``` This solution is cumbersome; tuple assignment is more elegant: > 這樣解決還是挺麻煩的;用元組賦值就更簡潔了: ```Python >>> a, b = b, a >>> a, b = b, a ``` The left side is a tuple of variables; the right side is a tuple of expressions. Each value is assigned to its respective variable. All the expressions on the right side are evaluated before any of the assignments. The number of variables on the left and the number of values on the right have to be the same: > 等號左邊的是變量組成的一個元組;右邊的是表達式的元組。每個值都被賦給了對應的變量。等號右邊的表達式的值保留了賦值之前的初始值。 > 等號左右兩側的變量和值的數目都必須是一樣的。 ```Python >>> a, b = 1, 2, 3 >>> a, b = 1, 2, 3 ValueError: too many values to unpack ``` More generally, the right side can be any kind of sequence (string, list or tuple). For example, to split an email address into a user name and a domain, you could write: > 更普適的情況下,等號右邊以是任意一種序列(字符串、列表或者元組)。比如,要把一個電子郵件地址轉換成一個用戶名和一個域名,可以用如下代碼實現: ```Python >>> addr = 'monty@python.org' >>> addr = 'monty@python.org' >>> uname, domain = addr.split('@') >>> uname, domain = addr.split('@') ``` The return value from split is a list with two elements; the first element is assigned to uname, the second to domain. > split 的返回值是一個有兩個元素的列表;第一個元素賦值給了 uname 這個變量,第二個賦值給了 domain 這個變量。 ```Python >>> uname >>> uname 'monty' >>> domain >>> domain 'python.org' ``` ## 12.3 Tuples as return values 用元組做返回值 Strictly speaking, a function can only return one value, but if the value is a tuple, the effect is the same as returning multiple values. For example, if you want to divide two integers and compute the quotient and remainder, it is inefficient to compute x/y and then x%y. It is better to compute them both at the same time. > 嚴格來說,一個函數只能返回一個值,但如果這個值是一個元組,效果就和返回多個值一樣了。例如,如果你想要將兩個整數相除,計算商和余數,如果要分開計算 x/y 以及 x%y 就很麻煩了。更好的辦法是同時計算這兩個值。 The built-in function divmod takes two arguments and returns a tuple of two values, the quotient and remainder. You can store the result as a tuple: > 內置函數 divmod 就會接收兩個參數,然后返回一個有兩個值的元組,這兩個值分別為商和余數。 > 可以把結果存儲為一個元組: ```Python >>> t = divmod(7, 3) >>> t = divmod(7, 3) >>> t >>> t (2, 1) ``` Or use tuple assignment to store the elements separately: > 或者可以用元組賦值來分別存儲這兩個值: ```Python >>> quot, rem = divmod(7, 3) >>> quot, rem = divmod(7, 3) >>> quot >>> quot 2 >>> rem >>> rem 1 ``` Here is an example of a function that returns a tuple: > 下面的例子中,函數返回一個元組作為返回值: ```Python def min_max(t): return min(t), max(t) ``` max and min are built-in functions that find the largest and smallest elements of a sequence. min_max computes both and returns a tuple of two values. > max 和 min 都是內置函數,會找到序列中的最大值或者最小值,min_max 這個函數會同時求得最大值和最小值,然后把這兩個值作為元組來返回。 ## 12.4 Variable-length argument tuples 參數長度可變的元組 Functions can take a variable number of arguments. A parameter name that begins with * gathers arguments into a tuple. For example, printall takes any number of arguments and prints them: > 函數的參數可以有任意多個。用星號*開頭來作為形式參數名,可以將所有實際參數收錄到一個元組中。例如 printall 就可以獲取任意多個數的參數,然后把它們都打印輸出: ```Python def printall(*args): print(args) ``` The gather parameter can have any name you like, but args is conventional. Here’s how the function works: > 你可以隨意命名收集來的這些參數,但 args 這個是約定俗成的慣例。下面展示一下這個函數如何使用: ```Python >>> printall(1, 2.0, '3') >>> printall(1, 2.0, '3') (1, 2.0, '3') ``` The complement of gather is scatter. If you have a sequence of values and you want to pass it to a function as multiple arguments, you can use the *operator. For example, divmod takes exactly two arguments; it doesn’t work with a tuple: > 與聚集相對的就是分散了。如果有一系列的值,然后想把它們作為多個參數傳遞給一個函數,就可以用星號*運算符。比如 divmod 要求必須是兩個參數;如果給它一個元組,是不能進行運算的: ```Python >>> t = (7, 3) >>> t = (7, 3) >>> divmod(t) >>> divmod(t) TypeError: divmod expected 2 arguments, got 1 ``` But if you scatter the tuple, it works: > 但如果拆分這個元組,就可以了: ```Python >>> divmod(*t) >>> divmod(*t) (2, 1) ``` Many of the built-in functions use variable-length argument tuples. For example, max and min can take any number of arguments: > 很多內置函數都用到了參數長度可變的元組。比如 max 和 min 就可以接收任意數量的參數: ```Python >>> max(1, 2, 3) >>> max(1, 2, 3) 3 ``` But sum does not. > 但求和函數 sum 就不行了。 ```Python >>> sum(1, 2, 3) >>> sum(1, 2, 3) TypeError: sum expected at most 2 arguments, got 3 ``` As an exercise, write a function called sumall that takes any number of arguments and returns their sum. > 做個練習,寫一個名為 sumall 的函數,讓它可以接收任意數量的參數,返回總和。 ## 12.5 Lists and tuples 列表和元組 zip is a built-in function that takes two or more sequences and returns a list of tuples where each tuple contains one element from each sequence. The name of the function refers to a zipper, which joins and interleaves two rows of teeth. This example zips a string and a list: > zip 是一個內置函數,接收兩個或更多的序列作為參數,然后返回返回一個元組列表,該列表中每個元組都包含了從各個序列中的一個元素。這個函數名的意思就是拉鎖,就是把不相關的兩排拉鎖齒連接到一起。 > 下面這個例子中,一個字符串和一個列表通過 zip 這個函數連接到了一起: ```Python >>> s = 'abc' >>> s = 'abc' >>> t = [0, 1, 2] >>> t = [0, 1, 2] >>> zip(s, t) >>> zip(s, t) <zip object at 0x7f7d0a9e7c48> ``` The result is a zip object that knows how to iterate through the pairs. The most common use of zip is in a for loop: > 該函數的返回值是一個 zip 對象,該對象可以用來迭代所有的數值對。zip 函數經常被用到 for 循環中: ```Python >>> for pair in zip(s, t): ... >>> for pair in zip(s, t): ... print(pair) ... ('a', 0) ('b', 1) ('c', 2) ``` A zip object is a kind of iterator, which is any object that iterates through a sequence. Iterators are similar to lists in some ways, but unlike lists, you can’t use an index to select an element from an iterator. If you want to use list operators and methods, you can use a zip object to make a list: > zip 對象是一種迭代器,也就是某種可以迭代整個序列的對象。迭代器和列表有些相似,但不同于列表的是,你無法通過索引來選擇迭代器中的指定元素。 > 如果想用列表的運算符和方法,可以用 zip 對象來構成一個列表: ```Python >>> list(zip(s, t)) >>> list(zip(s, t)) [('a', 0), ('b', 1), ('c', 2)] ``` The result is a list of tuples; in this example, each tuple contains a character from the string and the corresponding element from the list. If the sequences are not the same length, the result has the length of the shorter one. > 返回值是一個由元組構成的列表;在這個例子中,每個元組都包含了字符串中的一個字母,以及列表中對應位置的元素。 > 在長度不同的序列中,返回的結果長度取決于最短的一個。 ```Python >>> list(zip('Anne', 'Elk')) >>> list(zip('Anne', 'Elk')) [('A', 'E'), ('n', 'l'), ('n', 'k')] ``` You can use tuple assignment in a for loop to traverse a list of tuples: > 用 for 循環來遍歷一個元組列表的時候,可以用元組賦值語句: ```Python t = [('a', 0), ('b', 1), ('c', 2)] for letter, number in t: print(number, letter) ``` Each time through the loop, Python selects the next tuple in the list and assigns the elements to letter and number. The output of this loop is: > 每次經歷循環的時候,Python 都選中列表中的下一個元組,然后把元素賦值給字母和數字。該循環的輸出如下: ```Python 0 a 1 b 2 c ``` If you combine zip, for and tuple assignment, you get a useful idiom for traversing two (or more) sequences at the same time. For example, has_match takes two sequences, t1 and t2, and returns True if there is an index i such that t1[i] == t2[i]: > 如果結合使用 zip、for 循環以及元組賦值,就能得到一種能同時遍歷兩個以上序列的代碼組合。比如下面例子中的 has_match 這個函數,接收兩個序列t1和 t2作為參數,然后如果存在一個索引位置 i 使得 t1[i] == t2[i]就返回真: ```Python def has_match(t1, t2): for x, y in zip(t1, t2): if x == y: return True return False ``` If you need to traverse the elements of a sequence and their indices, you can use the built-in function enumerate: > 如果你要遍歷一個序列中的所有元素以及它們的索引,可以用內置的函數 enumerate: ```Python for index, element in enumerate('abc'): print(index, element) ``` The result from enumerate is an enumerate object, which iterates a sequence of pairs; each pair contains an index (starting from 0) and an element from the given sequence. In this example, the output is ```Python 0 a 1 b 2 c ``` Again. > enumerate 函數的返回值是一個枚舉對象,它會遍歷整個成對序列;每一對都包括一個索引(從0開始)以及給定序列的一個元素。在本節的例子中,輸出依然如下: > ```Python 0 a 1 b 2 c ``` ## 12.6 Dictionaries and tuples 詞典與元組 Dictionaries have a method called items that returns a sequence of tuples, where each tuple is a key-value pair. > 字典有一個名為 items 的方法,會返回一個由元組組成的序列,每一個元組都是字典中的一個鍵值對。 ```Python >>> d = {'a':0, 'b':1, 'c':2} >>> d = {'a':0, 'b':1, 'c':2} >>> t = d.items() >>> t = d.items() >>> t >>> t dict_items([('c', 2), ('a', 0), ('b', 1)]) ``` The result is a dict_items object, which is an iterator that iterates the key-value pairs. You can use it in a for loop like this: > 結果是一個 dict_items 對象,這是一個迭代器,迭代所有的鍵值對。可以在 for 循環里面用這個對象,如下所示: ```Python >>> for key, value in d.items(): >>> for key, value in d.items(): ... print(key, value) ... c 2 a 0 b 1 ``` As you should expect from a dictionary, the items are in no particular order. Going in the other direction, you can use a list of tuples to initialize a new dictionary: > 你也應該預料到了,字典里面的項是沒有固定順序的。 > 反過來使用的話,你就也可以用一個元組的列表來初始化一個新的字典: ```Python >>> t = [('a', 0), ('c', 2), ('b', 1)] >>> t = [('a', 0), ('c', 2), ('b', 1)] >>> d = dict(t) >>> d = dict(t) >>> d >>> d {'a': 0, 'c': 2, 'b': 1} ``` Combining dict with zip yields a concise way to create a dictionary: > 結合使用 dict 和 zip ,會得到一種建立字典的簡便方法: ```Python >>> d = dict(zip('abc', range(3))) >>> d = dict(zip('abc', range(3))) >>> d >>> d {'a': 0, 'c': 2, 'b': 1} ``` The dictionary method update also takes a list of tuples and adds them, as key-value pairs, to an existing dictionary. > 字典的 update 方法也接收一個元組列表,然后把它們作為鍵值對添加到一個已存在的字典中。 It is common to use tuples as keys in dictionaries (primarily because you can’t use lists). For example, a telephone directory might map from last-name, first-name pairs to telephone numbers. Assuming that we have defined last, first and number, we could write: > 把元組用作字典中的鍵是很常見的做法(主要也是因為這種情況不能用列表)。比如,一個電話字典可能就映射了姓氏、名字的數據對到不同的電話號碼。假如我們定義了 last,first 和 number 這三個變量,可以用如下方法來實現: ```Python directory[last, first] = number ``` The expression in brackets is a tuple. We could use tuple assignment to traverse this dictionary. > 方括號內的表達式是一個元組。我們可以用元組賦值語句來遍歷這個字典。 ```Python for last, first in directory: print(first, last, directory[last,first]) ``` This loop traverses the keys in directory, which are tuples. It assigns the elements of each tuple to last and first, then prints the name and corresponding telephone number. > 上面這個循環會遍歷字典中的鍵,這些鍵都是元組。程序會把每個元組的元素分別賦值給 last 和 first,然后輸出名字以及對應的電話號。 There are two ways to represent tuples in a state diagram. The more detailed version shows the indices and elements just as they appear in a list. For example, the tuple ('Cleese', 'John') would appear as in Figure 12.1. > 在狀態圖中表示元組的方法有兩種。更詳盡的版本會展示索引和元素,就如同在列表中一樣。例如圖12.1中展示了元組('Cleese', 'John') 。 * * * ![Figure 12.1: State diagram](http://7xnq2o.com1.z0.glb.clouddn.com/ThinkPython12.1.png) Figure 12.1: State diagram. * * * But in a larger diagram you might want to leave out the details. For example, a diagram of the telephone directory might appear as in Figure 12.2. > 但隨著圖解規模變大,你也許需要省略掉一些細節。比如電話字典的圖解可能會像圖12.2所示。 * * * ![Figure 12.2: State diagram](http://7xnq2o.com1.z0.glb.clouddn.com/ThinkPython12.2.png) Figure 12.2: State diagram. * * * Here the tuples are shown using Python syntax as a graphical shorthand. The telephone number in the diagram is the complaints line for the BBC, so please don’t call it. > 圖中的元組用 Python 的語法來簡單表示。其中的電話號碼是 BBC 的投訴熱線,所以不要給人家打電話哈。 ## 12.7 Sequences of sequences 序列的序列 I have focused on lists of tuples, but almost all of the examples in this chapter also work with lists of lists, tuples of tuples, and tuples of lists. To avoid enumerating the possible combinations, it is sometimes easier to talk about sequences of sequences. > 之前我一直在講由元組組成的列表,但本章幾乎所有的例子也適用于由列表組成的列表、元組組成的元組以及列表組成的元組。為了避免枚舉所有的組合,咱們直接討論序列組成的序列就更方便一些。 In many contexts, the different kinds of sequences (strings, lists and tuples) can be used interchangeably. So how should you choose one over the others? > 很多情況下,不同種類的序列(字符串、列表和元組)是可以交換使用的。那么該如何選擇用哪種序列呢? To start with the obvious, strings are more limited than other sequences because the elements have to be characters. They are also immutable. If you need the ability to change the characters in a string (as opposed to creating a new string), you might want to use a list of characters instead. > 先從最簡單的開始,字符串比起其他序列,功能更加有限,因為字符串中的元素必須是字符。而且還不能修改。如果你要修改字符串里面的字符(而不是要建立一個新字符串),你最好還是用字符列表吧。 Lists are more common than tuples, mostly because they are mutable. But there are a few cases where you might prefer tuples: > 列表用的要比元組更廣泛,主要因為列表可以修改。但以下這些情況下,你還是用元組更好: 1. In some contexts, like a return statement, it is syntactically simpler to create a tuple than a list. > 在某些情況下,比如返回語句中,用元組來實現語法上要比列表簡單很多。 2. If you want to use a sequence as a dictionary key, you have to use an immutable type like a tuple or string. > 如果你要用一個序列作為字典的鍵,必須用元組或者字符串這樣不可修改的類型才行。 3. If you are passing a sequence as an argument to a function, using tuples reduces the potential for unexpected behavior due to aliasing. > 如果你要把一個序列作為參數傳給一個函數,用元組能夠降低由于別名使用導致未知情況而帶來的風險。 Because tuples are immutable, they don’t provide methods like sort and reverse, which modify existing lists. But Python provides the built-in function sorted, which takes any sequence and returns a new list with the same elements in sorted order, and reversed, which takes a sequence and returns an iterator that traverses the list in reverse order. > 由于元組是不可修改的,所以不提供 sort 和 reverse 這樣的方法,這些方法都只能修改已經存在的列表。但 Python 提供了內置函數 sorted,該函數接收任意序列,然后返回一個把該序列中元素重新排序過的列表,另外還有個內置函數 reversed,接收一個序列然后返回一個以逆序迭代整個列表的迭代器。 ## 12.8 Debugging 調試 Lists, dictionaries and tuples are examples of data structures; in this chapter we are starting to see compound data structures, like lists of tuples, or dictionaries that contain tuples as keys and lists as values. Compound data structures are useful, but they are prone to what I call shape errors; that is, errors caused when a data structure has the wrong type, size, or structure. For example, if you are expecting a list with one integer and I give you a plain old integer (not in a list), it won’t work. > 列表、字典以及元組,都是數據結構的一些樣例;在本章我們開始見識這些復合的數據結構,比如由元組組成的列表,或者包含元組作為鍵而列表作為鍵值的字典等等。符合數據結構非常有用,但容易導致一些錯誤,我把這種錯誤叫做結構錯誤;這種錯誤往往是由于一個數據結構中出現了錯誤的類型、大小或者結構而引起的。比如,如果你想要一個由一個整形構成的列表,而我給你一個單純的整形變量(不是放進列表的),就會出錯了。 To help debug these kinds of errors, I have written a module called structshape that provides a function, also called structshape, that takes any kind of data structure as an argument and returns a string that summarizes its shape. You can download it from [Here](http://thinkpython2.com/code/structshape.py). > 要想有助于解決這類錯誤,我寫了一個叫做structshape 的模塊,該模塊提供了一個同名函數,接收任何一種數據結構作為參數,然后返回一個字符串來總結該數據結構的形態。可以從 [這里](http://thinkpython2.com/code/structshape.py)下載。 Here’s the result for a simple list: > 下面是一個簡單列表的示范: ```Python >>> from structshape import structshape >>> from structshape import structshape >>> t = [1, 2, 3] >>> t = [1, 2, 3] >>> structshape(t) >>> structshape(t) 'list of 3 int' ``` A fancier program might write “list of 3 ints”, but it was easier not to deal with plurals. Here’s a list of lists: > 更帶勁點的程序可能還應該寫“list of 3 ints”,但不理會單復數變化有利于簡化問題。下面是一個列表的列表: ```Python >>> t2 = [[1,2], [3,4], [5,6]] >>> t2 = [[1,2], [3,4], [5,6]] >>> structshape(t2) >>> structshape(t2) 'list of 3 list of 2 int' ``` If the elements of the list are not the same type, structshape groups them, in order, by type: > 如果列表元素是不同類型,structshape 會按照順序,把每種類型都列出: ```Python >>> t3 = [1, 2, 3, 4.0, '5', '6', [7], [8], 9] >>> t3 = [1, 2, 3, 4.0, '5', '6', [7], [8], 9] >>> structshape(t3) >>> structshape(t3) 'list of (3 int, float, 2 str, 2 list of int, int)' ``` Here’s a list of tuples: > 下面是一個元組的列表: ```Python >>> s = 'abc' >>> s = 'abc' >>> lt = list(zip(t, s)) >>> lt = list(zip(t, s)) >>> structshape(lt) >>> structshape(lt) 'list of 3 tuple of (int, str)' ``` And here’s a dictionary with 3 items that map integers to strings. > 下面是一個有三個項的字典,該字典映射了從整形數到字符串。 ```Python >>> d = dict(lt) >>> d = dict(lt) >>> structshape(d) >>> structshape(d) 'dict of 3 int->str' ``` If you are having trouble keeping track of your data structures, structshape can help. > 如果你追蹤自己的數據結構有困難,structshape這個模塊能有所幫助。 ## 12.9 Glossary 術語列表 tuple: An immutable sequence of elements. > 元組:一列元素組成的不可修改的序列。 tuple assignment: An assignment with a sequence on the right side and a tuple of variables on the left. The right side is evaluated and then its elements are assigned to the variables on the left. > 元組賦值:一種賦值語句,等號右側用一個序列,左側為一個變量構成的元組。右側的內容先進行運算,然后這些元素會賦值給左側的變量。 gather: The operation of assembling a variable-length argument tuple. > 收集:變量長度可變元組添加元素的運算。 scatter: The operation of treating a sequence as a list of arguments. > 分散:將一個序列拆分成一系列參數組成的列表的運算。 zip object: The result of calling a built-in function zip; an object that iterates through a sequence of tuples. > 拉鏈對象:調用內置函數 zip 得到的返回結果;一個遍歷元組序列的對象。 iterator: An object that can iterate through a sequence, but which does not provide list operators and methods. > 迭代器:迭代一個序列的對象,這種序列不能提供列表的運算和方法。 data structure: A collection of related values, often organized in lists, dictionaries, tuples, etc. > 數據結構:一些有關系數據的集合體,通常是列表、字典或者元組等形式。 shape error: An error caused because a value has the wrong shape; that is, the wrong type or size. > 結構錯誤:由于一個值有錯誤的結構而導致的錯誤;比如錯誤的類型或者大小。 ## 12.10 Exercises 練習 ### Exercise 1 練習1 Write a function called most_frequent that takes a string and prints the letters in decreasing order of frequency. Find text samples from several different languages and see how letter frequency varies between languages. Compare your results with the tables at [Here](http://en.wikipedia.org/wiki/Letter_frequencies). [Solution](http://thinkpython2.com/code/most_frequent.py). > 寫一個名為most_frequent的函數,接收一個字符串,然后用出現頻率降序來打印輸出字母。找一些不同語言的文本素材,然后看看不同語言情況下字母的頻率變化多大。然后用你的結果與[這里](http://en.wikipedia.org/wiki/Letter_frequencies)的數據進行對比。[樣例代碼](http://thinkpython2.com/code/most_frequent.py)。 ### Exercise 2 練習2 More anagrams! > 更多變位詞了! 1. Write a program that reads a word list from a file (see Section 9.1) and prints all the sets of words that are anagrams. > 寫一個函數,讀取一個文件中的一個單詞列表(參考9.1),然后輸出所有的變位詞。 Here is an example of what the output might look like: > 下面是可能的輸出樣式的示范: ['deltas', 'desalt', 'lasted', 'salted', 'slated', 'staled'] ['retainers', 'ternaries'] ['generating', 'greatening'] ['resmelts', 'smelters', 'termless'] Hint: you might want to build a dictionary that maps from a collection of letters to a list of words that can be spelled with those letters. The question is, how can you represent the collection of letters in a way that can be used as a key? > 提示:你也許可以建立一個字典,映射一個特定的字母組合到一個單詞列表,單詞列表中的單詞可以用這些字母來拼寫出來。那么問題來了,如何去表示這個字母的集合,才能讓這個集合能用作字典的一個鍵? 2. Modify the previous program so that it prints the longest list of anagrams first, followed by the second longest, and so on. > 修改一下之前的程序,讓它先輸出變位詞列表中最長的,然后是其次長的,依此類推。 3. In Scrabble a “bingo” is when you play all seven tiles in your rack, along with a letter on the board, to form an eight-letter word. What collection of 8 letters forms the most possible bingos? Hint: there are seven. [Solution](http://thinkpython2.com/code/anagram_sets.py). > 在拼字游戲中,當你已經有七個字母的時候,再添加一個字母就能組成一個八個字母的單詞,這就 TMD『bingo』 了(什么鬼東西?老外者拼字游戲就跟狗一樣,翻著惡心死了)。然后哪八個字母組合起來最可能得到 bingo?提示:有七個。(簡直就是狗一樣的題目,麻煩死了,這里數據結構大家學會了就好了。) ### Exercise 3 練習3 Two words form a “metathesis pair” if you can transform one into the other by swapping two letters; for example, “converse” and “conserve”. Write a program that finds all of the metathesis pairs in the dictionary. Hint: don’t test all pairs of words, and don’t test all possible swaps. [Solution](http://thinkpython2.com/code/metathesis.py). Credit: This exercise is inspired by an example at [Here](http://puzzlers.org). > 兩個單詞,如果其中一個通過調換兩個字母位置就能成為另外一個,就成了一個『交換對』。協議額函數來找到詞典中所有的這樣的交換對。提示:不用測試所有的詞對,不用測試所有可能的替換方案。[樣例代碼](http://thinkpython2.com/code/metathesis.py)。 鳴謝:本練習受啟發于[這里](http://puzzlers.org)的一個例子。 ### Exercise 4 練習4 Here’s another [Car Talk Puzzler](http://www.cartalk.com/content/puzzlers): > 接下來又是一個[汽車廣播字謎](http://www.cartalk.com/content/puzzlers): What is the longest English word, that remains a valid English word, as you remove its letters one at a time? Now, letters can be removed from either end, or the middle, but you can’t rearrange any of the letters. Every time you drop a letter, you wind up with another English word. If you do that, you’re eventually going to wind up with one letter and that too is going to be an English word—one that’s found in the dictionary. I want to know what’s the longest word and how many letters does it have? > 一個英文單詞,每次去掉一個字母,又還是一個正確的英文單詞,這是什么詞? > 然后接下來字母可以從頭去掉,也可以從末尾去掉,或者從中間,但不能重新排列其他字母。每次去掉一個字母,都會的到一個新的英文單詞。然后最終會得到一個字母,也還是一個英文單詞,這個單詞也能在詞典中找到。符合這樣要求的單詞有多少?最長的是哪個? I’m going to give you a little modest example: Sprite. Ok? You start off with sprite, you take a letter off, one from the interior of the word, take the r away, and we’re left with the word spite, then we take the e off the end, we’re left with spit, we take the s off, we’re left with pit, it, and I. > 給你一個合適的小例子:Sprite。這個詞就滿足上面的條件。把 r 去掉了是 spite,去掉結尾的 e 是 spit,去掉 s 得到的是 pit,it,然后是 I。 Write a program to find all words that can be reduced in this way, and then find the longest one. This exercise is a little more challenging than most, so here are some suggestions: > 寫一個函數找到所有的這樣的詞,然后找到其中最長的一個。 > 這個練習比一般的練習難以些,所以下面是一些提示: 1. You might want to write a function that takes a word and computes a list of all the words that can be formed by removing one letter. These are the “children” of the word. > 你也許需要寫一個函數,接收一個單詞然后計算一下這個單詞去掉一個字母能得到單詞組成的列表。列表中這些單詞就如同原始單詞的孩子一樣。 2. Recursively, a word is reducible if any of its children are reducible. As a base case, you can consider the empty string reducible. > 只要一個 單詞的孩子還可以縮減,那這個單詞本身就虧縮減。你可以認為空字符串是可以縮減的,這樣來作為一個基準條件。 3. The wordlist I provided, words.txt, doesn’t contain single letter words. So you might want to add “I”, “a”, and the empty string. > 我上面提供的 words.txt 這個詞表,不包含單個字母的單詞。所以你需要自行添加 I、a 以及空字符串上去。 4. To improve the performance of your program, you might want to memoize the words that are known to be reducible. > 要提高程序性能的話,你最好存儲住已經算出來能被繼續縮減的單詞。 [Solution](http://thinkpython2.com/code/reducible.py). > [樣例代碼](http://thinkpython2.com/code/reducible.py)。
                  <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>

                              哎呀哎呀视频在线观看