Home > Article > Backend Development > Python basic learning summary (4)
If a list or tuple is given, we can traverse the list or tuple through a for loop. This traversal is called iteration. In Python, iteration is done with for...in.
Because dict is not stored in the order of a list, the order of iterated results is likely to be different. By default, dict iterates over keys. If you want to iterate value, you can use for value in d.values(). If you want to iterate key and value at the same time, you can use for k, v in d.items().
Since strings are also iterable objects, they can also be used in for loops:
>>> for ch in 'ABC': ... Print(ch) ... A B C |
How to determine whether an object is an iterable object? The method is to judge by the Iterable type of the collections module:
>>> from collections import Iterable >>> isinstance('abc', Iterable) # Whether str is iterable True >>> isinstance([1,2,3], Iterable) # Whether list is iterable True >>> isinstance(123, Iterable) # Whether the integer is iterable False |
What if you want to implement a subscript loop similar to Java on the list? Python's built-in enumerate function can turn a list into an index-element pair, so that the index and the element itself can be iterated at the same time in a for loop:
>>> for i, value in enumerate(['A', 'B', 'C']): ... Print(i, value) ... 0 A 1 B 2 C |
List Comprehensions are a very simple but powerful built-in Python generation that can be used to create lists.
To generate a list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], you can use list(range(1, 11)).
When writing a list generation expression, put the element x * You can also add an if judgment after the for loop, so that we can filter out only the squares of even numbers:
>>> [x * x for x in range(1, 11) if x % 2 == 0] [4, 16, 36, 64, 100] |
You can also use a two-level 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'] |
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, change all the strings in a list to lowercase:
>>> L = ['Hello', 'World', 'IBM', 'Apple'] >>> [s.lower() for s in L] ['hello', 'world', 'ibm', 'apple'] |
If the elements of the list can be calculated according to a certain algorithm, subsequent elements can be continuously calculated during the loop. In Python, this mechanism of calculating while looping is called a generator: generator.
There are many ways to create a generator. The first method is very simple. Just change [] to () in a list generation expression to create a generator:
>>> 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 |
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 them out one by one, you can get the next return value of the generator through the next() function. As we have said, the generator saves the algorithm. Every time next(g) is called, the value of the next element of g is calculated until the last element is calculated. When there are no more elements, a 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 call last): File " StopIteration |
The correct way is to use a for loop, because generator is also an iterable 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 a generator. If a function definition contains the yield keyword, then the function is no longer an ordinary 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' |
We assign the elements in the tuple ('Tokyo', 2003, 32450, 0.66, 8014) to the variables city, year, pop, chg and area respectively, and we write all the assignments with only one line of declaration . Similarly, in the next line, a % operator maps the elements in the passport tuple to the format string gaps in the print function. Both of these are applications of tuple unpacking.
The most recognizable form of tuple unpacking is parallel assignment, that is, assigning the elements in an iterable object to a tuple composed 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 split an iterable object as a function parameter:
>>> divmod(20, 8) (2, 4) >>> t = (20, 8) >>> divmod(*t) (twenty four) >>> quotient, remainder = divmod(*t) >>> quotient, remainder (twenty four) |
The usage of tuple unpacking here is to allow a function to return multiple values in the form of tuples, and then the code calling the function can easily accept these return values. For example, the os.path.split() function will return a tuple consisting of the path and the last file name (path, last_part):
>>> import os >>> _, filename = os.path.split('/home/luciano/.ssh/idrsa.pub') >>> filename 'idrsa.pub’ |
In Python, it is a classic way of writing a function to use *args to obtain an uncertain number of parameters.
In Python 3, this concept has been 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 in front of a variable name, but this variable can 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) |
The above is the detailed content of Python basic learning summary (4). For more information, please follow other related articles on the PHP Chinese website!