Python's list-generation can put the elements to be generated x*x in front, followed by A For loop, this is Python-specific list generation, can be very concise code to generate a list.
ex:>>> [x * x for x in range (1, 11)]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Range (1,100,2) can generate [1,3,5,7.......97,99] Use this pattern to generate a more flexible list.
Iterations that use a for loop can iterate not only the normal list, but also the dict.
Assume the dict of the following:
D = {' Adam ': ' Lisa ': ' n ', ' Bart ': 59}
It can be turned into an HTML table by a complex list-generation:
TDS = [' <tr><td>%s</td><td>%s</td></tr> '% (name, score) for name, score in D.iteritems ()]
print ' <table> '
print ' <tr><th>name</th><th>score</th ><tr> '
print ' \ n '. Join (TDS)
print ' </table> '
Note: The string can be formatted by%, replacing%s with the specified parameter. The join () method of a string can concatenate a list into a string.
Save the printed results as an HTML file, and you can see the effect in the 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>
The For loop for the list generation can also be followed by an if judgment. For example:
>>> [x * x for x in range (1, one)]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
If we only want even squared, without changing range (), we can add if to filter:
>>> [x * x for x in range (1, one) if x 2 = 0]
[4, C, M] the
following is a capitalization of all the strings in the list collection, not a string ignored
D EF touppers (L): Return
[X.upper () to X in L if Isinstance (x,str)]
print touppers ([' Hello ', ' World ', 101])
A For loop can be nested, so you can also use a multi-tier for loop to generate a list in a list-generation.
For the string ' ABC ' and ' 123 ', you can use a two-tier loop to generate a full arrangement:
>>> [M + N for m in ' ABC ' for n in ' 123 ']
[' A1 ', ' A2 ', ' A3 ', ' B1 ', ' B2 ', ' B3 ', ' C1 ', ' C2 ', ' C3 ']
Translate it into looping code as follows:
L = [] for
m in ' ABC ': for
N in ' 123 ':
l.append (M + N)