present (sb for a job etc)
This article focuses on the basics and use of list generators in Python
Generating Lists
To generate list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], we can use range(1, 11):
>>> range(1, 11) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
But to generate [1x1, 2x2, 3x3, ... , 10x10] how to do it? Method one is a loop:
>>> L = [] >>> for x in range(1, 11): ... (x * x) ... >>> L [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
But loops are too cumbersome, whereas list generators can generate the list above with a single line instead of a loop:
>>> [x * x for x in range(1, 11)] [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
This way of writing is Python-specific list generator. With list generators, lists can be generated in very clean code.
When writing a list generator, put the element x * x to be generated in front, followed by a for loop, you can create the list, very useful, write a few more times, you will soon be familiar with this syntax.
Complex Expressions (TODO)
Iteration using a for loop can iterate not only over normal lists, but also over dicts.
Suppose there is the following dict:
d = { 'Adam': 95, 'Lisa': 85, 'Bart': 59 }
It's possible to turn it into an HTML table with a complex list builder:
tds = ['<tr><td>%s</td><td>%s</td></tr>' % (name, score) for name, score in ()] print '<table>' print '<tr><th>Name</th><th>Score</th><tr>' print '\n'.join(tds) print '</table>'
Note: Strings can be formatted with % by replacing %s with the specified parameter. the join() method for strings can splice a list into a string.
Save the printout as an html file and you can see the results in your browser:
<table border="1"> <tr><th>Name</th><th>Score</th><tr> <tr><td>Lisa</td><td>85</td></tr> <tr><td>Adam</td><td>95</td></tr> <tr><td>Bart</td><td>59</td></tr> </table>
conditional filtering
The for loop of a list generator can be followed by an if judgment. For example:
>>> [x * x for x in range(1, 11)] [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
If we only want even squares, without changing range(), we can add if to filter:
>>> [x * x for x in range(1, 11) if x % 2 == 0] [4, 16, 36, 64, 100]
With the if condition, the current element of the loop is added to the list only if the if judgment is True.
multilayer expression
For loops can be nested, so it is also possible to generate lists with multiple layers of for loops in a list generator.
For the strings 'ABC' and '123', a two-level loop can be used to generate the full permutation:
>>> [m + n for m in 'ABC' for n in '123'] ['A1', 'A2', 'A3', 'B1', 'B2', 'B3', 'C1', 'C2', 'C3']
Translated into looping code it looks like the following:
L = [] for m in 'ABC': for n in '123': (m + n)
concluding remarks
Above is the introduction to python development - list generator details, more information about python list generator please pay attention to my other related articles!