Advanced Features
Iteration
Given a list or tuple, we can use for
to traverse the list or tuple cycle, which we call traversal iteration (Iteration).
In Python, iteration through for ... in
to complete, and many languages such as C language, the iteration list is completed by the index, such as the Java code:
for (i=0; i<list.length; i++) {
n = list[i];
}
As can be seen, the Python for
cycle abstraction than the C for
cycle because the Python for
cycle can be used not only in the tuple list or, may also act on other objects iteration.
Although this data type list under the standard, but a lot of other data types are not under the subject, but, as long as iterables, with or without subscript, can be iterative, such as dict can be iterative:
>>> d = {'a': 1, 'b': 2, 'c': 3}
>>> for key in d:
... print(key)
...
a
c
b
Because the storage is not dict order list in accordance with the way, so that the result of the iteration sequence is likely to be different.
By default, dict iteration is key. If you want iteration value, it can be used for value in d.values()
, If you want iteration key and value, can be used for k, v in d.items()
.
Because the string is iterables, therefore, it may be applied to the for loop:
>>> for ch in 'ABC':
... print(ch)
...
A
B
C
So, when we use for
the loop, as long as the acts on an iteration object for
loop can operate normally, and we do not care whether the object is a list or other data types.
So, how to judge an object is iterable it? It is determined by the type Iterable collections module:
>>> from collections import Iterable
>>> isinstance('abc', Iterable) # str是否可迭代
True
>>> isinstance([1,2,3], Iterable) # list是否可迭代
True
>>> isinstance(123, Iterable) # 整数是否可迭代
False
One final question, if you want to achieve subscript circulation list as Java-like how to do? Python built-in enumerate
functions can be turned into a list index - the element right, so that you can simultaneously iteration index and the element itself in a for loop:
>>> for i, value in enumerate(['A', 'B', 'C']):
... print(i, value)
...
0 A
1 B
2 C
Above for loop, also references two variables in Python is very common, for example, the following code:
>>> for x, y in [(1, 1), (2, 4), (3, 9)]:
... print(x, y)
...
1 1
2 4
3 9
List of Formula
That list of Formula List Comprehensions, Python is a very simple but powerful built-in can be used to create a list of the formula.
For example, to generate a list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
can be used list(range(1, 11))
:
>>> list(range(1, 11))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
But if you want to generate [1x1, 2x2, 3x3, ..., 10x10]
how to do? The first loop method:
>>> L = []
>>> for x in range(1, 11):
... L.append(x * x)
...
>>> L
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
However, the cycle too complicated, and the list of the formula may be replaced with a circulation line list generated above statement:
>>> [x * x for x in range(1, 11)]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
When writing a list of the formula, the element to be generated x * x
to the front, followed by a for loop, you can create a list out, is useful to write a few times, will soon be familiar with this syntax.
can also add back loop for determining if, so that we can filter out only the even square of:
>>> [x * x for x in range(1, 11) if x % 2 == 0]
[4, 16, 36, 64, 100]
May also be used two cycles, the whole arrangement can be generated:
>>> [m + n for m in 'ABC' for n in 'XYZ']
['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']
More than three and a triple loop is rarely used.
Use the formula list, you can write very simple code. For example, to list all files and directories in the current directory, can be achieved through a line of code:
>>> import os # 导入os模块,模块的概念后面讲到
>>> [d for d in os.listdir('.')] # os.listdir可以列出文件和目录
['.emacs.d', '.ssh', '.Trash', 'Adlm', 'Applications', 'Desktop', 'Documents', 'Downloads', 'Library', 'Movies', 'Music', 'Pictures', 'Public', 'VirtualBox VMs', 'Workspace', 'XCode']
for
In fact, recycling can simultaneously use two or more variables, such as dict
the items()
possible iterations key and value at the same time:
>>> d = {'x': 'A', 'y': 'B', 'z': 'C' }
>>> for k, v in d.items():
... print(k, '=', v)
...
y = B
x = A
z = C
Thus, the list formula may be used to generate two variables list:
>>> d = {'x': 'A', 'y': 'B', 'z': 'C' }
>>> [k + '=' + v for k, v in d.items()]
['y=B', 'x=A', 'z=C']
Finally a list of all the strings to lowercase:
>>> L = ['Hello', 'World', 'IBM', 'Apple']
>>> [s.lower() for s in L]
['hello', 'world', 'ibm', 'apple']
if ... else
using a list of formula of time, some children's shoes often do not know if ... else usage.
For example, the following code is the even normal:
>>> [x for x in range(1, 11) if x % 2 == 0]
[2, 4, 6, 8, 10]
But we can not in the final if
plus else
:
>>> [x for x in range(1, 11) if x % 2 == 0 else 0]
File "<stdin>", line 1
[x for x in range(1, 11) if x % 2 == 0 else 0]
^
SyntaxError: invalid synta
This is because with the for
back of if
a filter condition, can not take else
, or how to screen?
Other children's shoes found the if
writing for
must be added to the front else
, otherwise an error:
>>> [x if x % 2 == 0 for x in range(1, 11)]
File "<stdin>", line 1
[x if x % 2 == 0 for x in range(1, 11)]
^
SyntaxError: invalid syntax
This is because for
the front part is an expression, it must be based on x
a result of the calculation. Therefore, study the expression: x if x % 2 == 0
it can not be based on x
the results of the calculation, because of the lack else
, must be added else
:
>>> [x if x % 2 == 0 else -x for x in range(1, 11)]
[-1, 2, -3, 4, -5, 6, -7, 8, -9, 10]
Above for
the preceding expression x if x % 2 == 0 else -x
can be the basis x
of the computation results of the determination.
It is seen in a formula list in for
front of if ... else
an expression, and for the latter if
is a filter, not with else
.