Python BASICS (IV) and python Basics
6. 6.1 iteration of Higher-Order features
If a list or tuple is given, we can use the for loop to traverse the list or tuple. This traversal is called Iteration ). In Python, iterations are completed through for... in.
Because the storage of dict is not arranged in the order of list, the order of iteration results may be different. By default, key is iterated by dict. If you want to iterate value, you can use for value in d. values (). If you want to iterate both key and value, you can use for k, v in d. items ().
Because the string is also an iteratable object, it can also act on the for Loop:
>>> For ch in 'abc ': ... Print (ch) ... A B C |
How can I determine whether an object is an Iterated object? The method is determined by the Iterable type of the collections module:
>>> From collections import Iterable >>> Isinstance ('abc', Iterable) # Can str be iterated? True >>> Isinstance ([1, 2, 3], Iterable) # Whether list can be iterated True >>> Isinstance (123, Iterable) # Whether the integer can be iterated False |
What if I want to implement subscript loop like Java for list? Python's built-in enumerate function can convert a list into an index-element pair, so that the index and element itself can be iterated simultaneously in the for Loop:
>>> For I, value in enumerate (['A', 'B', 'C']): ... Print (I, value) ... 0 1 B 2 C |
6.2 list Derivation
The List generator is list Comprehensions, which is a simple but powerful built-in form that can be used to create a List.
To generate a list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], you can use list (range (1, 11 )).
When writing the list generator, put the x element to be generated in front, followed by the for loop, you can create the list, which is very useful and can be written several times more, you will soon be familiar with this syntax. The for loop can be followed by the if judgment, so that we can filter out only the even square:
>>> [X * x for x in range (1, 11) if x % 2 = 0] [4, 16, 36, 64,100] |
You can also use a two-layer loop to generate a full arrangement:
>>> [M + n for m in 'abc' for n in 'xyz'] ['Ax ', 'ay', 'az', 'bx ', 'by', 'bz', 'cx', 'cy ', 'cz'] |
The list generator can also use two variables to generate the list:
>>> D = {'X': 'A', 'y': 'B', 'z': 'C '} >>> [K + '=' + v for k, v in d. items ()] ['Y = B ', 'X = A', 'z = C'] |
Finally, convert all strings in a list 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 a certain algorithm, the subsequent elements can be constantly calculated during the loop process. In Python, this one-side loop-Side Computing mechanism is called generator: generator.
There are many ways to create a generator. The first method is very simple. You only need to change [] of a list generator type to (), and 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 L and g is that the [] and () of the outermost layer, L is a list, and g is a generator. To print them one by one, you can use the next () function to obtain the next return value of generator. As we have mentioned, generator stores algorithms. Every time next (g) is called, the value of the next element of g is calculated until the last element is computed and no more elements exist, throw the StopIteration error.
>>> 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 call last ): File "<stdin>", line 1, in <module> StopIteration |
The correct method is to use a for loop, because generator is also an iteratable 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 method for defining generator. If a function definition contains the yield keyword, this function is no longer a common 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 tuples
We assign the elements in the tuples ('Tokyo ', 2003,324 50, 0.66, 8014) to the variables city, year, pop, chg, and area, respectively, all the values are written with only one declaration. Similarly, in the next row, a % operator maps the elements in the passport tuples to the empty Format String file of the print function. These two are the application of the tuples for unpacking.
The best way to identify tuples is to assign values in parallel. That is to say, the elements in an Iterated object are assigned values to the tuples composed of corresponding variables.
Parallel assignment:
>>> Lax_coordinates = (33.9425,-118.408056) >>> Latitude, longpolling = lax_coordinates # split tuples >>> Latitude 33.9425 >>> Longpolling -118.408056 |
Use the * operator to split an iteratable 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) |
Here, the rule used to split tuples is to allow a function to return multiple values in the form of tuples, and then the code that calls the function can easily accept the returned values. For example, the OS. path. split () function returns the tuples (path, last_part) consisting of the path and the last file name ):
>>> Import OS >>> _, Filename = OS. path. split ('/home/luciano/. ssh/idrsa. pub ') >>> Filename 'Idrsa. pub' |
In Python, the function uses * args to obtain uncertain numbers of parameters.
In Python 3, this concept is extended to parallel assignment:
>>> 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 assignment, * the prefix can only be used before a variable name, but this variable can appear in any position of 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) |