Ignore:
Timestamp:
Mar 19, 2014, 11:31:01 PM (11 years ago)
Author:
dmik
Message:

python: Merge vendor 2.7.6 to trunk.

Location:
python/trunk
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • python/trunk

  • python/trunk/Doc/tutorial/datastructures.rst

    r2 r391  
    171171the sequence for which ``function(item)`` is true. If *sequence* is a
    172172:class:`string` or :class:`tuple`, the result will be of the same type;
    173 otherwise, it is always a :class:`list`. For example, to compute some primes::
     173otherwise, it is always a :class:`list`. For example, to compute a sequence of
     174numbers not divisible by 2 or 3::
    174175
    175176   >>> def f(x): return x % 2 != 0 and x % 3 != 0
     
    229230and works exactly like this.
    230231
    231 .. versionadded:: 2.3
    232 
     232.. _tut-listcomps:
    233233
    234234List Comprehensions
    235235-------------------
    236236
    237 List comprehensions provide a concise way to create lists without resorting to
    238 use of :func:`map`, :func:`filter` and/or :keyword:`lambda`. The resulting list
    239 definition tends often to be clearer than lists built using those constructs.
    240 Each list comprehension consists of an expression followed by a :keyword:`for`
    241 clause, then zero or more :keyword:`for` or :keyword:`if` clauses.  The result
    242 will be a list resulting from evaluating the expression in the context of the
    243 :keyword:`for` and :keyword:`if` clauses which follow it.  If the expression
    244 would evaluate to a tuple, it must be parenthesized. ::
    245 
     237List comprehensions provide a concise way to create lists.
     238Common applications are to make new lists where each element is the result of
     239some operations applied to each member of another sequence or iterable, or to
     240create a subsequence of those elements that satisfy a certain condition.
     241
     242For example, assume we want to create a list of squares, like::
     243
     244   >>> squares = []
     245   >>> for x in range(10):
     246   ...     squares.append(x**2)
     247   ...
     248   >>> squares
     249   [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
     250
     251We can obtain the same result with::
     252
     253   squares = [x**2 for x in range(10)]
     254
     255This is also equivalent to ``squares = map(lambda x: x**2, range(10))``,
     256but it's more concise and readable.
     257
     258A list comprehension consists of brackets containing an expression followed
     259by a :keyword:`for` clause, then zero or more :keyword:`for` or :keyword:`if`
     260clauses.  The result will be a new list resulting from evaluating the expression
     261in the context of the :keyword:`for` and :keyword:`if` clauses which follow it.
     262For example, this listcomp combines the elements of two lists if they are not
     263equal::
     264
     265   >>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
     266   [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
     267
     268and it's equivalent to:
     269
     270   >>> combs = []
     271   >>> for x in [1,2,3]:
     272   ...     for y in [3,1,4]:
     273   ...         if x != y:
     274   ...             combs.append((x, y))
     275   ...
     276   >>> combs
     277   [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
     278
     279Note how the order of the :keyword:`for` and :keyword:`if` statements is the
     280same in both these snippets.
     281
     282If the expression is a tuple (e.g. the ``(x, y)`` in the previous example),
     283it must be parenthesized. ::
     284
     285   >>> vec = [-4, -2, 0, 2, 4]
     286   >>> # create a new list with the values doubled
     287   >>> [x*2 for x in vec]
     288   [-8, -4, 0, 4, 8]
     289   >>> # filter the list to exclude negative numbers
     290   >>> [x for x in vec if x >= 0]
     291   [0, 2, 4]
     292   >>> # apply a function to all the elements
     293   >>> [abs(x) for x in vec]
     294   [4, 2, 0, 2, 4]
     295   >>> # call a method on each element
    246296   >>> freshfruit = ['  banana', '  loganberry ', 'passion fruit  ']
    247297   >>> [weapon.strip() for weapon in freshfruit]
    248298   ['banana', 'loganberry', 'passion fruit']
    249    >>> vec = [2, 4, 6]
    250    >>> [3*x for x in vec]
    251    [6, 12, 18]
    252    >>> [3*x for x in vec if x > 3]
    253    [12, 18]
    254    >>> [3*x for x in vec if x < 2]
    255    []
    256    >>> [[x,x**2] for x in vec]
    257    [[2, 4], [4, 16], [6, 36]]
    258    >>> [x, x**2 for x in vec]  # error - parens required for tuples
    259      File "<stdin>", line 1, in ?
    260        [x, x**2 for x in vec]
     299   >>> # create a list of 2-tuples like (number, square)
     300   >>> [(x, x**2) for x in range(6)]
     301   [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
     302   >>> # the tuple must be parenthesized, otherwise an error is raised
     303   >>> [x, x**2 for x in range(6)]
     304     File "<stdin>", line 1
     305       [x, x**2 for x in range(6)]
    261306                  ^
    262307   SyntaxError: invalid syntax
    263    >>> [(x, x**2) for x in vec]
    264    [(2, 4), (4, 16), (6, 36)]
    265    >>> vec1 = [2, 4, 6]
    266    >>> vec2 = [4, 3, -9]
    267    >>> [x*y for x in vec1 for y in vec2]
    268    [8, 6, -18, 16, 12, -36, 24, 18, -54]
    269    >>> [x+y for x in vec1 for y in vec2]
    270    [6, 5, -7, 8, 7, -5, 10, 9, -3]
    271    >>> [vec1[i]*vec2[i] for i in range(len(vec1))]
    272    [8, 12, -54]
    273 
    274 List comprehensions are much more flexible than :func:`map` and can be applied
    275 to complex expressions and nested functions::
    276 
    277    >>> [str(round(355/113.0, i)) for i in range(1,6)]
     308   >>> # flatten a list using a listcomp with two 'for'
     309   >>> vec = [[1,2,3], [4,5,6], [7,8,9]]
     310   >>> [num for elem in vec for num in elem]
     311   [1, 2, 3, 4, 5, 6, 7, 8, 9]
     312
     313List comprehensions can contain complex expressions and nested functions::
     314
     315   >>> from math import pi
     316   >>> [str(round(pi, i)) for i in range(1, 6)]
    278317   ['3.1', '3.14', '3.142', '3.1416', '3.14159']
    279318
    280319
    281320Nested List Comprehensions
    282 --------------------------
    283 
    284 If you've got the stomach for it, list comprehensions can be nested. They are a
    285 powerful tool but -- like all powerful tools -- they need to be used carefully,
    286 if at all.
    287 
    288 Consider the following example of a 3x3 matrix held as a list containing three
    289 lists, one list per row::
    290 
    291     >>> mat = [
    292     ...        [1, 2, 3],
    293     ...        [4, 5, 6],
    294     ...        [7, 8, 9],
    295     ...       ]
    296 
    297 Now, if you wanted to swap rows and columns, you could use a list
    298 comprehension::
    299 
    300     >>> print [[row[i] for row in mat] for i in [0, 1, 2]]
    301     [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
    302 
    303 Special care has to be taken for the *nested* list comprehension:
    304 
    305     To avoid apprehension when nesting list comprehensions, read from right to
    306     left.
    307 
    308 A more verbose version of this snippet shows the flow explicitly::
    309 
    310     for i in [0, 1, 2]:
    311         for row in mat:
    312             print row[i],
    313         print
    314 
    315 In real world, you should prefer built-in functions to complex flow statements.
     321''''''''''''''''''''''''''
     322
     323The initial expression in a list comprehension can be any arbitrary expression,
     324including another list comprehension.
     325
     326Consider the following example of a 3x4 matrix implemented as a list of
     3273 lists of length 4::
     328
     329   >>> matrix = [
     330   ...     [1, 2, 3, 4],
     331   ...     [5, 6, 7, 8],
     332   ...     [9, 10, 11, 12],
     333   ... ]
     334
     335The following list comprehension will transpose rows and columns::
     336
     337   >>> [[row[i] for row in matrix] for i in range(4)]
     338   [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
     339
     340As we saw in the previous section, the nested listcomp is evaluated in
     341the context of the :keyword:`for` that follows it, so this example is
     342equivalent to::
     343
     344   >>> transposed = []
     345   >>> for i in range(4):
     346   ...     transposed.append([row[i] for row in matrix])
     347   ...
     348   >>> transposed
     349   [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
     350
     351which, in turn, is the same as::
     352
     353   >>> transposed = []
     354   >>> for i in range(4):
     355   ...     # the following 3 lines implement the nested listcomp
     356   ...     transposed_row = []
     357   ...     for row in matrix:
     358   ...         transposed_row.append(row[i])
     359   ...     transposed.append(transposed_row)
     360   ...
     361   >>> transposed
     362   [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
     363
     364
     365In the real world, you should prefer built-in functions to complex flow statements.
    316366The :func:`zip` function would do a great job for this use case::
    317367
    318     >>> zip(*mat)
    319     [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
     368   >>> zip(*matrix)
     369   [(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]
    320370
    321371See :ref:`tut-unpacking-arguments` for details on the asterisk in this line.
     
    373423   >>> u
    374424   ((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
     425   >>> # Tuples are immutable:
     426   ... t[0] = 88888
     427   Traceback (most recent call last):
     428     File "<stdin>", line 1, in <module>
     429   TypeError: 'tuple' object does not support item assignment
     430   >>> # but they can contain mutable objects:
     431   ... v = ([1, 2, 3], [3, 2, 1])
     432   >>> v
     433   ([1, 2, 3], [3, 2, 1])
     434
    375435
    376436As you see, on output tuples are always enclosed in parentheses, so that nested
    377437tuples are interpreted correctly; they may be input with or without surrounding
    378438parentheses, although often parentheses are necessary anyway (if the tuple is
    379 part of a larger expression).
    380 
    381 Tuples have many uses.  For example: (x, y) coordinate pairs, employee records
    382 from a database, etc.  Tuples, like strings, are immutable: it is not possible
    383 to assign to the individual items of a tuple (you can simulate much of the same
    384 effect with slicing and concatenation, though).  It is also possible to create
    385 tuples which contain mutable objects, such as lists.
     439part of a larger expression).  It is not possible to assign to the individual
     440items of a tuple, however it is possible to create tuples which contain mutable
     441objects, such as lists.
     442
     443Though tuples may seem similar to lists, they are often used in different
     444situations and for different purposes.
     445Tuples are :term:`immutable`, and usually contain an heterogeneous sequence of
     446elements that are accessed via unpacking (see later in this section) or indexing
     447(or even by attribute in the case of :func:`namedtuples <collections.namedtuple>`).
     448Lists are :term:`mutable`, and their elements are usually homogeneous and are
     449accessed by iterating over the list.
    386450
    387451A special problem is the construction of tuples containing 0 or 1 items: the
     
    412476packing and sequence unpacking.
    413477
    414 .. XXX Add a bit on the difference between tuples and lists.
    415 
    416478
    417479.. _tut-sets:
     
    424486eliminating duplicate entries.  Set objects also support mathematical operations
    425487like union, intersection, difference, and symmetric difference.
     488
     489Curly braces or the :func:`set` function can be used to create sets.  Note: to
     490create an empty set you have to use ``set()``, not ``{}``; the latter creates an
     491empty dictionary, a data structure that we discuss in the next section.
    426492
    427493Here is a brief demonstration::
     
    451517   set(['r', 'd', 'b', 'm', 'z', 'l'])
    452518
     519Similarly to :ref:`list comprehensions <tut-listcomps>`, set comprehensions
     520are also supported::
     521
     522   >>> a = {x for x in 'abracadabra' if x not in 'abc'}
     523   >>> a
     524   set(['r', 'd'])
     525
    453526
    454527.. _tut-dictionaries:
     
    482555The :meth:`keys` method of a dictionary object returns a list of all the keys
    483556used in the dictionary, in arbitrary order (if you want it sorted, just apply
    484 the :meth:`sort` method to the list of keys).  To check whether a single key is
    485 in the dictionary, use the :keyword:`in` keyword.
     557the :func:`sorted` function to it).  To check whether a single key is in the
     558dictionary, use the :keyword:`in` keyword.
    486559
    487560Here is a small example using a dictionary::
     
    502575   True
    503576
    504 The :func:`dict` constructor builds dictionaries directly from lists of
    505 key-value pairs stored as tuples.  When the pairs form a pattern, list
    506 comprehensions can compactly specify the key-value list. ::
     577The :func:`dict` constructor builds dictionaries directly from sequences of
     578key-value pairs::
    507579
    508580   >>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
    509581   {'sape': 4139, 'jack': 4098, 'guido': 4127}
    510    >>> dict([(x, x**2) for x in (2, 4, 6)])     # use a list comprehension
     582
     583In addition, dict comprehensions can be used to create dictionaries from
     584arbitrary key and value expressions::
     585
     586   >>> {x: x**2 for x in (2, 4, 6)}
    511587   {2: 4, 4: 16, 6: 36}
    512 
    513 Later in the tutorial, we will learn about Generator Expressions which are even
    514 better suited for the task of supplying key-values pairs to the :func:`dict`
    515 constructor.
    516588
    517589When the keys are simple strings, it is sometimes easier to specify pairs using
     
    526598Looping Techniques
    527599==================
    528 
    529 When looping through dictionaries, the key and corresponding value can be
    530 retrieved at the same time using the :meth:`iteritems` method. ::
    531 
    532    >>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
    533    >>> for k, v in knights.iteritems():
    534    ...     print k, v
    535    ...
    536    gallahad the pure
    537    robin the brave
    538600
    539601When looping through a sequence, the position index and corresponding value can
     
    582644   orange
    583645   pear
     646
     647When looping through dictionaries, the key and corresponding value can be
     648retrieved at the same time using the :meth:`iteritems` method. ::
     649
     650   >>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
     651   >>> for k, v in knights.iteritems():
     652   ...     print k, v
     653   ...
     654   gallahad the pure
     655   robin the brave
     656
     657To change a sequence you are iterating over while inside the loop (for
     658example to duplicate certain items), it is recommended that you first make
     659a copy.  Looping over a sequence does not implicitly make a copy.  The slice
     660notation makes this especially convenient::
     661
     662   >>> words = ['cat', 'window', 'defenestrate']
     663   >>> for w in words[:]:  # Loop over a slice copy of the entire list.
     664   ...     if len(w) > 6:
     665   ...         words.insert(0, w)
     666   ...
     667   >>> words
     668   ['defenestrate', 'cat', 'window', 'defenestrate']
    584669
    585670
Note: See TracChangeset for help on using the changeset viewer.