Changeset 391 for python/trunk/Doc/tutorial/datastructures.rst
- Timestamp:
- Mar 19, 2014, 11:31:01 PM (11 years ago)
- Location:
- python/trunk
- Files:
-
- 2 edited
Legend:
- Unmodified
- Added
- Removed
-
python/trunk
-
Property svn:mergeinfo
set to
/python/vendor/Python-2.7.6 merged eligible /python/vendor/current merged eligible
-
Property svn:mergeinfo
set to
-
python/trunk/Doc/tutorial/datastructures.rst
r2 r391 171 171 the sequence for which ``function(item)`` is true. If *sequence* is a 172 172 :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:: 173 otherwise, it is always a :class:`list`. For example, to compute a sequence of 174 numbers not divisible by 2 or 3:: 174 175 175 176 >>> def f(x): return x % 2 != 0 and x % 3 != 0 … … 229 230 and works exactly like this. 230 231 231 .. versionadded:: 2.3 232 232 .. _tut-listcomps: 233 233 234 234 List Comprehensions 235 235 ------------------- 236 236 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 237 List comprehensions provide a concise way to create lists. 238 Common applications are to make new lists where each element is the result of 239 some operations applied to each member of another sequence or iterable, or to 240 create a subsequence of those elements that satisfy a certain condition. 241 242 For 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 251 We can obtain the same result with:: 252 253 squares = [x**2 for x in range(10)] 254 255 This is also equivalent to ``squares = map(lambda x: x**2, range(10))``, 256 but it's more concise and readable. 257 258 A list comprehension consists of brackets containing an expression followed 259 by a :keyword:`for` clause, then zero or more :keyword:`for` or :keyword:`if` 260 clauses. The result will be a new list resulting from evaluating the expression 261 in the context of the :keyword:`for` and :keyword:`if` clauses which follow it. 262 For example, this listcomp combines the elements of two lists if they are not 263 equal:: 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 268 and 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 279 Note how the order of the :keyword:`for` and :keyword:`if` statements is the 280 same in both these snippets. 281 282 If the expression is a tuple (e.g. the ``(x, y)`` in the previous example), 283 it 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 246 296 >>> freshfruit = [' banana', ' loganberry ', 'passion fruit '] 247 297 >>> [weapon.strip() for weapon in freshfruit] 248 298 ['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)] 261 306 ^ 262 307 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 313 List 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)] 278 317 ['3.1', '3.14', '3.142', '3.1416', '3.14159'] 279 318 280 319 281 320 Nested 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 323 The initial expression in a list comprehension can be any arbitrary expression, 324 including another list comprehension. 325 326 Consider the following example of a 3x4 matrix implemented as a list of 327 3 lists of length 4:: 328 329 >>> matrix = [ 330 ... [1, 2, 3, 4], 331 ... [5, 6, 7, 8], 332 ... [9, 10, 11, 12], 333 ... ] 334 335 The 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 340 As we saw in the previous section, the nested listcomp is evaluated in 341 the context of the :keyword:`for` that follows it, so this example is 342 equivalent 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 351 which, 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 365 In the real world, you should prefer built-in functions to complex flow statements. 316 366 The :func:`zip` function would do a great job for this use case:: 317 367 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)] 320 370 321 371 See :ref:`tut-unpacking-arguments` for details on the asterisk in this line. … … 373 423 >>> u 374 424 ((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 375 435 376 436 As you see, on output tuples are always enclosed in parentheses, so that nested 377 437 tuples are interpreted correctly; they may be input with or without surrounding 378 438 parentheses, 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. 439 part of a larger expression). It is not possible to assign to the individual 440 items of a tuple, however it is possible to create tuples which contain mutable 441 objects, such as lists. 442 443 Though tuples may seem similar to lists, they are often used in different 444 situations and for different purposes. 445 Tuples are :term:`immutable`, and usually contain an heterogeneous sequence of 446 elements 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>`). 448 Lists are :term:`mutable`, and their elements are usually homogeneous and are 449 accessed by iterating over the list. 386 450 387 451 A special problem is the construction of tuples containing 0 or 1 items: the … … 412 476 packing and sequence unpacking. 413 477 414 .. XXX Add a bit on the difference between tuples and lists.415 416 478 417 479 .. _tut-sets: … … 424 486 eliminating duplicate entries. Set objects also support mathematical operations 425 487 like union, intersection, difference, and symmetric difference. 488 489 Curly braces or the :func:`set` function can be used to create sets. Note: to 490 create an empty set you have to use ``set()``, not ``{}``; the latter creates an 491 empty dictionary, a data structure that we discuss in the next section. 426 492 427 493 Here is a brief demonstration:: … … 451 517 set(['r', 'd', 'b', 'm', 'z', 'l']) 452 518 519 Similarly to :ref:`list comprehensions <tut-listcomps>`, set comprehensions 520 are also supported:: 521 522 >>> a = {x for x in 'abracadabra' if x not in 'abc'} 523 >>> a 524 set(['r', 'd']) 525 453 526 454 527 .. _tut-dictionaries: … … 482 555 The :meth:`keys` method of a dictionary object returns a list of all the keys 483 556 used 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 is485 in thedictionary, use the :keyword:`in` keyword.557 the :func:`sorted` function to it). To check whether a single key is in the 558 dictionary, use the :keyword:`in` keyword. 486 559 487 560 Here is a small example using a dictionary:: … … 502 575 True 503 576 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. :: 577 The :func:`dict` constructor builds dictionaries directly from sequences of 578 key-value pairs:: 507 579 508 580 >>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)]) 509 581 {'sape': 4139, 'jack': 4098, 'guido': 4127} 510 >>> dict([(x, x**2) for x in (2, 4, 6)]) # use a list comprehension 582 583 In addition, dict comprehensions can be used to create dictionaries from 584 arbitrary key and value expressions:: 585 586 >>> {x: x**2 for x in (2, 4, 6)} 511 587 {2: 4, 4: 16, 6: 36} 512 513 Later in the tutorial, we will learn about Generator Expressions which are even514 better suited for the task of supplying key-values pairs to the :func:`dict`515 constructor.516 588 517 589 When the keys are simple strings, it is sometimes easier to specify pairs using … … 526 598 Looping Techniques 527 599 ================== 528 529 When looping through dictionaries, the key and corresponding value can be530 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, v535 ...536 gallahad the pure537 robin the brave538 600 539 601 When looping through a sequence, the position index and corresponding value can … … 582 644 orange 583 645 pear 646 647 When looping through dictionaries, the key and corresponding value can be 648 retrieved 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 657 To change a sequence you are iterating over while inside the loop (for 658 example to duplicate certain items), it is recommended that you first make 659 a copy. Looping over a sequence does not implicitly make a copy. The slice 660 notation 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'] 584 669 585 670
Note:
See TracChangeset
for help on using the changeset viewer.