6. High-order features 6.1 iterations
Given a list or tuple, we can traverse the list or tuple through a for loop, which we call iteration (iteration). In Python, an iteration is done through a for ... in.
Because Dict storage is not ordered in list order, the resulting order of the iterations is likely to be different. By default, the Dict iteration is key. If you want to iterate over value, you can use for value in D.values (), if you want to iterate both key and value at the same time, you can use a for-K, V in D.items ().
Because a string is also an iterative object, it can also be used for A For loop:
>>> for ch in ' ABC ': ... print (CH) ... A B C |
Determine if an object is an iterative object? The method is judged by the iterable type of the collections module:
>>> from collections Import iterable >>> isinstance (' abc ', iterable) # whether STR can iterate True >>> ([isinstance], iterable) # Whether the list can be iterated True >>> isinstance (123, iterable) # integers can be iterated False |
What if you want to implement subscript loops like Java for a list? Python's built-in enumerate function can turn a list into an index-element pair so that both the index and the element itself can be iterated in the For loop:
>>> for I, value in enumerate ([' A ', ' B ', ' C '): .. print (i, value) ... 0 A 1 B 1 ' |
6.2 List Derivation
The list generation, which is the comprehensions, is a very simple and powerful build of Python built-in that can be used to create lists.
To generate list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] You can use List (range (1, 11)).
When writing list generation, put the element x * x to the front, followed by the For loop, you can create a list, very useful, write a few more times, you will soon be familiar with this syntax. The For loop can also be followed by an if judgment so that we can filter out only the even squares:
>>> [x * x for x in range (1, one) if x% 2 = = 0] [4, 16, 36, 64, 100] |
You can also use a two-layer loop to generate a full array:
>>> [M + N for m in ' ABC ' for n in ' XYZ '] [' AX ', ' AY ', ' AZ ', ' BX ', ' by ', ' BZ ', ' CX ', ' CY ', ' CZ '] |
List generation can also use two variables to generate a list:
>>> d = {' X ': ' A ', ' y ': ' B ', ' z ': ' C '} >>> [k + ' = ' + V for K, V in D.items ()] [' Y=b ', ' x=a ', ' z=c '] |
Finally, all the strings in a list are converted to lowercase:
>>> L = [' Hello ', ' World ', ' IBM ', ' Apple '] >>> [S.lower () for s in L] [' Hello ', ' World ', ' IBM ', ' Apple '] |
6.3 Generator Expression
If the list element can be calculated according to an algorithm, you can continue to calculate the subsequent elements in the process of the loop, in Python, this side loop side of the computation mechanism, called the generator: Generator.
There are a number of ways to create a generator. The first method is simple, as long as a list-generated [] is changed to (), a generator is created:
>>> L = [x * x for x in range (10)] >>> L [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] >>> g = (x * x for x in range (10)) >>> g <generator Object <genexpr> at 0x1022ef630> |
The difference between creating L and G is only the outermost [] and (), L is a list, and G is a generator. If you want to print one, you can get the next return value of generator with the next () function. As we've said, generator saves the algorithm, and each time we call next (g), it calculates the value of the next element of G, until the last element is calculated, and when there are no more elements, the Stopiteration error is thrown.
>>> Next (g) 0 >>> Next (g) 1 >>> Next (g) 4 >>> Next (g) 9 >>> Next (g) 16 >>> Next (g) 25 >>> Next (g) 36 >>> Next (g) 49 >>> Next (g) 64 >>> Next (g) 81 >>> Next (g) Traceback (most recent): File "<stdin>", line 1, in <module> Stopiteration |
The correct approach is to use a For loop because generator is also an iterative object:
>>> g = (x * x for x in range (10)) >>> for N in G: ... print (n) ... 0 1 4 9 16 25 36 49 64 81 |
Another way to define generator. If a function definition contains the yield keyword, then the function is no longer a normal function, but a generator:
def fib (max): N, a, b = 0, 0, 1 While n < max: Yield b A, B = B, A + b n = n + 1 Return ' Done ' |
6.4-Tuple unpacking
We assign the elements in the tuple (' Tokyo ', 2003, 32450, 0.66, 8014) to the variable city, year, pop, Chg, and area respectively, and all of these assignments are finished with just one line of declaration. Similarly, in the following line, a% operator corresponds to the element in the passport tuple to the format string neutral of the print function. Both of these are applications that are split against a tuple.
The best identification of a tuple is a parallel assignment, which means that the elements in an iterative object are assigned to a tuple of corresponding variables.
Parallel Assignment:
>>> lax_coordinates = (33.9425,-118.408056) >>> latitude, longitude = lax_coordinates # tuple Unpacking >>> Latitude 33.9425 >>> Longitude -118.408056 |
Use the * operator to disassemble an iterative object as a function parameter:
>>> Divmod (20, 8) (2, 4) >>> t = (20, 8) >>> Divmod (*t) (2, 4) >>> quotient, remainder = Divmod (*t) >>> Quotient, remainder (2, 4) |
The use of tuple unpacking here is to allow a function to return multiple values in the form of tuples, and then invoke the code of the function to easily accept the return values. For example, the Os.path.split () function returns a tuple (path, last_part) that consists of a path and a last file name:
>>> Import OS >>> _, filename = Os.path.split ('/home/luciano/.ssh/idrsa.pub ') >>> filename ' Idrsa.pub ' |
In Python, a function using *args to get an indeterminate number of parameters is a classic notation.
In Python 3, this concept is extended to parallel assignments:
>>> A, B, *rest = Range (5) >>> A, B, rest (0, 1, [2, 3, 4]) >>> A, B, *rest = Range (3) >>> A, B, rest (0, 1, [2]) >>> A, B, *rest = Range (2) >>> A, B, rest (0, 1, []) |
In parallel assignments, the * prefix can only be used in front of a variable name, but this variable may appear anywhere in the assignment expression:
>>> A, *body, C, d = Range (5) >>> A, body, C, D (0, [1, 2], 3, 4) >>> *head, B, c, d = Range (5) >>> Head, B, C, D ([0, 1], 2, 3, 4) |
Python Basic Learning Summary (iv)