The Python Tutorial 5——Data Structures

来源:互联网 发布:上海师范大学网络教育 编辑:程序博客网 时间:2024/05/17 21:58

updated at 2015.01.07

5.1. More on Lists

The list data type has some more methods.

>>> a = [66.25, 333, 333, 1, 1234.5]>>> print a.count(333), a.count(66.25), a.count('x')    #Return the number of times x appears in the list.2 1 0>>> a.insert(2, -1)>>> a.append(333)>>> a[66.25, 333, -1, 333, 1, 1234.5, 333]>>> a.index(333)    #Return the index in the list of the first item whose value is x. It is an error if there                    #is no such item.1>>> a.remove(333)    #Remove the first item from the list whose value is x. It is an error if thereis no such item.>>> 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()    #Remove the item at the given position in the list, and return it.  If no index is specified,a.pop()                #removes and returns the last item in the list.1234.5>>> a[-1, 1, 66.25, 333, 333]

5.1.1. Using Lists as Stacks

The list methods make it very easy to use a list as a stack, where the last element added is the first element retrieved (“last-in, first-out”). To add an item to the top of the stack, use append(). To retrieve an item from the top of the stack, use without an explicit index. For example:

>>> stack = [3]>>> stack.append(4)>>> stack[3, 4]>>> stack.pop()4>>> stack.pop()3>>> stack pop()Traceback (most recent call last):  File "<stdin>", line 1, in <module>IndexError: pop from empty list

5.1.2. Using Lists as Queues

To implement a queue, use collections.deque which was designed to have fast appends and pops from both ends. For example:
>>> 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 arrivaldeque(['Michael', 'Terry', 'Graham'])

5.1.3. Functional Programming Tools

There are three built-in functions that are very useful when used with lists:filter(),map(), and reduce().

filter(function,sequence)returns a sequence consisting of those items from the sequence for which function(item) is true. If sequence is astring ortuple, the result will be of the same type;otherwise, it is always alist. For example, to compute a sequence of numbers divisible by 3 or 5:

>>> def f(x): return x % 3 == 0 or x % 5 == 0...>>> filter(f, range(2, 25))[3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24]

map(function,sequence) calls function(item) for each of the sequence’s items and returns a list of the return values. For example, to compute some cubes:

>>> def cube(x): return x*x*x...>>> map(cube, range(1, 11))[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
>>> seq = range(8)>>> def add(x, y): return x+y...>>> map(add, seq, seq)   #注意参数个数要与函数要求的相同[0, 2, 4, 6, 8, 10, 12, 14]

reduce(function,sequence)returns asingle value constructed by calling the binary function(二元函数)function on the first two items of the sequence, then on the result and the next item, and so on. For example, to compute the sum of the numbers 1 through 10:

>>> def sum(seq):...     def add(x,y): return x+y...     return reduce(add, seq, 0)...>>> sum(range(1, 11))55>>> sum([])0


5.1.4. List Comprehensions

List comprehensions provide a concise way to create lists.
>>> s = [ x**2 for x in range(10)]>>> s[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
A list comprehension consists of brackets containing an expression followed by afor clause, then zero or morefor orif clauses.
>>> [(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)]

List comprehensions can contain complex expressions and nested functions:

>>> 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.2. The del statement

>>> 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[:]    #clear>>> a  []

del can also be used to delete entire variables:

>>> a = [1,3]>>> a[1, 3]>>> del a>>> aTraceback (most recent call last):  File "<stdin>", line 1, in <module>NameError: name 'a' is not defined
>>> aTraceback (most recent call last): File "<stdin>", line 1, in <module>NameError: name 'a' is not defined

5.3. Tuples and Sequences

A tuple consists of a number of values separated by commas, for instance:   与list的区别是tuple的值不可改变

>>> 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] = 88888Traceback (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 ispart 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.

list与tuple区别  Though tuples may seem similar to lists, they are often used in different situations and for different purposes.Tuples areimmutable, 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 ofnamed tuples).Lists aremutable, and their elements areusually homogeneous and are accessed by iterating over the list.

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:

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


5.4. Sets

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.

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.

Here is a brief demonstration:

>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']>>> fruit = set(basket)               # create a set without duplicates>>> fruitset(['orange', 'pear', 'apple', 'banana'])>>> 'orange' in fruit                 # fast membership testingTrue>>> 'crabgrass' in fruitFalse>>> # Demonstrate set operations on unique letters from two words...>>> a = set('abracadabra')>>> b = set('alacazam')>>> a                                  # unique letters in aset(['a', 'r', 'b', 'c', 'd'])>>> a - b                              # letters in a but not in bset(['r', 'd', 'b'])>>> a | b                              # letters in either a or bset(['a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'])>>> a & b                              # letters in both a and bset(['a', 'c'])>>> a ^ b                              # letters in a or b but not bothset(['r', 'd', 'b', 'm', 'z', 'l'])

>>> a = {x for x in 'abracadabra' if x not in 'abc'}>>> aset(['r', 'd'])

5.5. Dictionaries

hash

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().

It is best to think of a dictionary as an unordered set of key: value pairs,with the requirement that the keys areunique (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 isforgotten. It is an error to extract a value using a non-existent key.

The keys() method of a dictionary object returns a list of all the keys used in the dictionary, in arbitrary order (if you want it sorted, just apply  the sorted() function to it). To check whether a single key is in the dictionary, use thein keyword.

Here is a small example using a dictionary:

>>> 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}>>> tel.keys()['guido', 'irv', 'jack']>>> 'guido' in telTrue

The dict() constructor builds dictionaries directly from sequences of key-value pairs:

>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)]){'sape': 4139, 'jack': 4098, 'guido': 4127}

In addition, dict comprehensions can be used to create dictionaries fromarbitrary key and value expressions:

>>> {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 usingkeyword arguments:

>>> dict(sape=4139, guido=4127, jack=4098){'sape': 4139, 'jack': 4098, 'guido': 4127}

5.6. Looping Techniques

When looping through a sequence, the position index and corresponding value canbe retrieved at the same time using theenumerate() function.

>>> for i, v in enumerate(['tic', 'tac', 'toe']):...     print i, v...0 tic1 tac2 toe

To loop over two or more sequences at the same time, the entries can be paired with thezip() function.

>>> 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 sorted order, use the sorted() function whichreturns a new sorted list while leaving the source unaltered.

>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']>>> for f in sorted(set(basket)):...     print f...applebananaorangepear

When looping through dictionaries, the key and corresponding value can beretrieved at the same time using theiteritems() method.

>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}>>> for k, v in knights.iteritems():...     print k, v...gallahad the purerobin the brave

0 0
原创粉丝点击