There is a way to remove an item from a list given its index instead of its value: the del statement. This differs from the pop() method which returns a value. The del statement can also be used to remove slices from a list or clear the entire list (which we did earlier by assignment of an empty list to the slice). For example:html
del語句:刪除列表中指定位置的元素。與列表的pop()方法有點不一樣的是:del語句能夠刪除整個列表或者是移除子列表。例如:python
>>> 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 can also be used to delete entire variables:程序員
del還能夠刪除整個列表變量:express
>>> del a
Referencing the name a hereafter is an error (at least until another value is assigned to it). We’ll find other uses for del later.編程
如今引用a變量,則會出現錯誤。咱們將會在後面看到del另外的做用。app
We saw that lists and strings have many common properties, such as indexing and slicing operations. They are two examples of sequence data types (see Sequence Types — list, tuple, range). Since Python is an evolving language, other sequence data types may be added. There is also another standard sequence data type: the tuple.less
咱們已經看到列表和字符串有許多共同的屬性,例如索引和切片操做。他們只是序列類型的兩個例子(參考 序列類型--列表,元組,range)。由於Python正不斷的處於更新中,其餘序列類型可能會再被加進來。元組:另外一個標準的序列數據類型。編程語言
A tuple consists of a number of values separated by commas, for instance:ide
元組是由一些由逗號分隔的元素組成,例如:函數
>>> 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])
As you see, on output tuples are always enclosed in parentheses, so that nested tuples are interpreted correctly; they may be input with or without surrounding parentheses, although often parentheses are necessary anyway (if the tuple is part of a larger expression). It is not possible to assign to the individual items of a tuple, however it is possible to create tuples which contain mutable objects, such as lists.
正如你所看見的,元組的輸出老是用圓括號括起來,所以嵌套的元組能夠很好的被解釋器所識別;儘管元組經常須要加入圓括號(若是元組是一個較大表達式的一部分),但元組的輸入能夠加圓括號,也可不加。不能夠給元組的某個元素再賦值,然而,咱們能夠在建立元組的時候包含可變對象,好比列表。
Though tuples may seem similar to lists, they are often used in different situations and for different purposes. Tuples are immutable, and usually contain an heterogeneous sequence of elements that are accessed via unpacking (see later in this section) or indexing (or even by attribute in the case of namedtuples). Lists are mutable, and their elements are usually homogeneous and are accessed by iterating over the list.
儘管元組看起來和列表很類似,但他們經常用於不一樣的情形和目的。元組是不可變對象,一般包含不一樣類型的元素,並經過unpacking(解包)或索引訪問。列表是可變量,它的元素一般是同一種類型,並經過迭代對象訪問整個列表。
A special problem is the construction of tuples containing 0 or 1 items: the syntax has some extra quirks to accommodate these. Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses). Ugly, but effective. For example:
構造一個包含0個或1個元素的元組可能看上去有點特別:語法上有點怪異。空元組一般就是用一對空圓括號表示;包含一個元素的元組須要在該元素的後面加上一個逗號(對於單個元素的元組,圓括號無關緊要).看起來不夠優雅,可是頗有效。例如:
>>> empty = () >>> singleton = 'hello', # <-- note trailing comma >>> len(empty) 0 >>> len(singleton) 1 >>> singleton ('hello',)
The statement t = 12345, 54321, 'hello!' is an example of tuple packing: the values 12345, 54321 and 'hello!' are packed together in a tuple. The reverse operation is also possible:
語句 t = 12345, 54321, 'hello!' 是一個元組打包的例子:元素12345, 54321 and 'hello!'被元組包裹在一塊兒。相反的操做也是合法的:
>>> x, y, z = t
This is called, appropriately enough, sequence unpacking and works for any sequence on the right-hand side. Sequence unpacking requires that there are as many variables on the left side of the equals sign as there are elements in the sequence. Note that multiple assignment is really just a combination of tuple packing and sequence unpacking.
這個序列的解包調用例子,恰好合適。其餘序列均可以放到等號右邊做解包操做。序列的解包操做要求等號左邊的變量和序列右邊的元素個數要相同。注意,多重賦值僅僅只是元組的一個打包和解包的一個結合。
Python also includes a data type for sets. A set is an unordered collection with no duplicate elements. Basic uses include membership testing and eliminating duplicate entries. Set objects also support mathematical operations like union, intersection, difference, and symmetric difference.
Python還包含集合這種數據類型。一個集合是一個無序的、沒有重複元素的容器。集合最基本的用途是:檢查元素是否在集合中,以及排除重複元素。集合對象支持數學運算操做,例如:聯合、交集、difference(非?)、symmetric difference。
Curly braces or the set() function can be used to create sets. Note: to create an empty set you have to use set(), not {}; the latter creates an empty dictionary, a data structure that we discuss in the next section.
可使用花括號或set()函數來建立一個集合對象。注意:建立一個空的集合對象必須使用set(),不能使用{};咱們將會在下一節討論如何用{}建立一個空的字典。
Here is a brief demonstration:
舉幾個例子:
>>> 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'}
Similarly to list comprehensions, set comprehensions are also supported:
相似於 list comprehensions。集合也支持 set comprehensions:
>>> a = {x for x in 'abracadabra' if x not in 'abc'} >>> a {'r', 'd'}
Another useful data type built into Python is the dictionary (see Mapping Types — dict). Dictionaries are sometimes found in other languages as 「associative memories」 or 「associative arrays」. Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend().
另外一個Python內置的有用的數據類型是:字典。字典在其餘編程語言中可能被稱爲:"associative memories" 或者 "associative arrays"。與序列類型不一樣的是:字典是經過鍵來索引的,鍵必須是不可變類型; 鍵通常經常是字符串或數值類型。若是元組僅僅只包含字符串、數值或元組,則元組也能夠看成鍵; 若是元組中包含可變對象,不論是直接仍是間接包含都不能做爲索引。你不能把列表看成鍵,由於列表是可變對象。
It is best to think of a dictionary as an unordered set of key: value pairs, with the requirement that the keys are unique (within one dictionary). A pair of braces creates an empty dictionary: {}. Placing a comma-separated list of key:value pairs within the braces adds initial key:value pairs to the dictionary; this is also the way dictionaries are written on output.
咱們能夠把字典看做是無序的鍵:值 這樣的集合(鍵必須是惟一的)。可使用一對花括號建立一個空的字典{}。字典中鍵和值用分號隔開,每對鍵值用逗號隔開。
The main operations on a dictionary are storing a value with some key and extracting the value given the key. It is also possible to delete a key:value pair with del. If you store using a key that is already in use, the old value associated with that key is forgotten. It is an error to extract a value using a non-existent key.
字典的主要操做就是:存儲鍵值對,必要的時候再取出來。使用del 語句能夠很容易的刪除鍵值對。若是你使用了一個已經存儲了的鍵,那麼久的鍵值對就會被取代。使用一個沒存在的鍵提取值則會報錯。
Performing list(d.keys()) on a dictionary returns a list of all the keys used in the dictionary, in arbitrary order (if you want it sorted, just use sorted(d.keys()) instead). [2] To check whether a single key is in the dictionary, use the in keyword.
執行list(d.keys())操做,d是一個字典,則返回全部的鍵並存儲在列表中,他們在列表中的順序是無序的(若是你想排序,可使用sorted(d.keys()))。可使用關鍵字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
The dict() constructor builds dictionaries directly from sequences of key-value pairs:
dict()函數能夠直接從一個包含鍵值對的序列中建立一個字典。
>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)]) {'sape': 4139, 'jack': 4098, 'guido': 4127}
In addition, dict comprehensions can be used to create dictionaries from arbitrary key and value expressions:
另外,dict comprehensions也能建立任意個鍵值對的字典:
>>> {x: x**2 for x in (2, 4, 6)} {2: 4, 4: 16, 6: 36}
When the keys are simple strings, it is sometimes easier to specify pairs using keyword arguments:
若是鍵是簡單的字符串,咱們可使用關鍵字參數指定鍵值對:
>>> dict(sape=4139, guido=4127, jack=4098) {'sape': 4139, 'jack': 4098, 'guido': 4127}
When looping through dictionaries, the key and corresponding value can be retrieved at the same time using the items() method.
當遍歷字典的時候,可使用items()函數同時提取鍵和值。
>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'} >>> for k, v in knights.items(): ... print(k, v) ... gallahad the pure robin the brave
When looping through a sequence, the position index and corresponding value can be retrieved at the same time using the enumerate() function.
當遍歷序列的時候 。可使用enumerate()函數同時提取索引和對應的值。
>>> for i, v in enumerate(['tic', 'tac', 'toe']): ... print(i, v) ... 0 tic 1 tac 2 toe
To loop over two or more sequences at the same time, the entries can be paired with the zip() function.
當同時遍歷兩個序列時。可使用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.
To loop over a sequence in reverse, first specify the sequence in a forward direction and then call the reversed() function.
爲了變量反轉以後的序列,能夠調用reversed()函數。
>>> for i in reversed(range(1, 10, 2)): ... print(i) ... 9 7 5 3 1
To loop over a sequence in sorted order, use the sorted() function which returns a new sorted list while leaving the source unaltered.
想要有序的遍歷序列,可使用函數sorted()。該函數返回一個有序的列表,但元素在原序列中的順序是不變的。
>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'] >>> for f in sorted(set(basket)): ... print(f) ... apple banana orange pear
To change a sequence you are iterating over while inside the loop (for example to duplicate certain items), it is recommended that you first make a copy. Looping over a sequence does not implicitly make a copy. The slice notation makes this especially convenient:
若是在遍歷序列的時候想修改序列,建議先複製該序列。由於變量序列的時候不會顯示的去複製。切片操做(複製一個序列)很是適合這種狀況。
>>> 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']
The conditions used in while and if statements can contain any operators, not just comparisons.
while和if語句能夠包含任何操做返回的值,而不只僅是比較操做的條件判斷
The comparison operators in and not in check whether a value occurs (does not occur) in a sequence. The operators is and is not compare whether two objects are really the same object; this only matters for mutable objects like lists. All comparison operators have the same priority, which is lower than that of all numerical operators.
in和not in檢查值是否在序列中。is 和 is not 比較兩個對象是否是真正的爲同一個對象;這僅僅適用於可變對象,例如list(不可變對象能夠看着是值傳遞相關的操做,可變對象能夠看着是引用傳遞的操做)。全部的比較操做都有相同的優先級,比較操做優先級低於全部的數值運算。
Comparisons can be chained. For example, a < b == c tests whether a is less than b and moreover b equals c.
可以鏈式比較。例如: a < b == c 檢查 a 是否小於b 而且 b 是否等於 c。
Comparisons may be combined using the Boolean operators and and or, and the outcome of a comparison (or of any other Boolean expression) may be negated with not. These have lower priorities than comparison operators; between them, not has the highest priority and or the lowest, so that A and not B or C is equivalent to (A and (not B)) or C. As always, parentheses can be used to express the desired composition.
比較操做可使用布爾操做符:and 和 or 否認可使用not。他們的優先級低於比較操做符;他們中,not 具備最高的優先級,or最低。所以 A and not B or C 至關於 (A and (not B)) or C。所以儘可能養成加括號的習慣。
The Boolean operators and and or are so-called short-circuit operators: their arguments are evaluated from left to right, and evaluation stops as soon as the outcome is determined. For example, if A and C are true but B is false, A and B and C does not evaluate the expression C. When used as a general value and not as a Boolean, the return value of a short-circuit operator is the last evaluated argument.
布爾運算符and 和 or 有時被稱爲短路操做符:從左至右依次判斷結果,當獲得肯定的結果後,則後面的比較就再也不執行了,例如:若是 A和C爲真,B爲假,A and B and C將不會執行C操做。當使用其餘比較不使用布爾,則每一個表達式都會被執行。
It is possible to assign the result of a comparison or other Boolean expression to a variable. For example,
很容易將比較操做或布爾表達式賦值給某個變量。例如:
>>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance' >>> non_null = string1 or string2 or string3 >>> non_null 'Trondheim'
Note that in Python, unlike C, assignment cannot occur inside expressions. C programmers may grumble about this, but it avoids a common class of problems encountered in C programs: typing = in an expression when == was intended.
與C語言不通,在Python中,不能在表達式裏面賦值,C程序員可能以爲難以想象,可是這樣能避免在C語言中常見的一個錯誤:原本想書寫==卻寫了=。
Sequence objects may be compared to other objects with the same sequence type. The comparison uses lexicographical ordering: first the first two items are compared, and if they differ this determines the outcome of the comparison; if they are equal, the next two items are compared, and so on, until either sequence is exhausted. If two items to be compared are themselves sequences of the same type, the lexicographical comparison is carried out recursively. If all items of two sequences compare equal, the sequences are considered equal. If one sequence is an initial sub-sequence of the other, the shorter sequence is the smaller (lesser) one. Lexicographical ordering for strings uses the Unicode code point number to order individual characters. Some examples of comparisons between sequences of the same type:
相同序列類型的兩個序列對象也能夠作比較操做。他們使用邏輯順序比較:先是兩個序列的第一個元素比較,接着是兩個序列的第二個元素比較...直到知道結果後,則退出比較。若是兩個序列的全部元素都相等,那麼這兩個序列就相等,若是一個序列是另外一個序列的子序列,那麼這個子序列就小於父序列。字符串的比較是使用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)
Note that comparing objects of different types with < or > is legal provided that the objects have appropriate comparison methods. For example, mixed numeric types are compared according to their numeric value, so 0 equals 0.0, etc. Otherwise, rather than providing an arbitrary ordering, the interpreter will raise a TypeError exception.
注意:不一樣對象之間也能夠用 < 或者 > 進行比較,但被比較的對象具備合適的比較方法。例如,混合的數值類型經過值進行比較,所以 0 等於0.0。若是擁有的比較方法不合適,則會拋出TypeError異常。