This article mainly explains the actual application of the Python list generation formula! Hope to be helpful to beginners!
1. Complex list-generated HTML table:
Note: The string can be formatted in% with the specified parameterization instead of%s. The join () method of a string can be used to stitch a list into a string.
Mark not a few scores as red:
D = {' Adam ': +, ' Lisa ': $, ' Bart ': 59}
def generate_tr (name, score):
If score < 60
Return ' <tr><td>%s</td><td style= ' color:red >%s</td></tr> '% (name, score)
Return ' <tr><td>%s</td><td>%s</td></tr> '% (name, score)
TDS = [GENERATE_TR (name, score) for name, score in D.iteritems ()]
print ' <table border= ' 1 "> '
print ' <tr><th>Name</th><th>Score</th><tr> '
print ' \ n '. Join (TDS)
print ' </table> '
2. Conditional filtering
A list-generated for loop can also be followed by an if judgment:
Returns all strings in the list as uppercase, and non-string elements are ignored
Tips:
1, isintance (X,STR) can determine whether the variable x is a string
2. The upper () method of the string can return uppercase letters
def touppers (L):
return [X.upper () for x in L if Isinstance (X,STR)]
Print touppers ([' Hello ', ' World ', 101])
3. Multi-layer expression
For loops can be nested, so the list can be generated using a multi-layer for loop
such as: For the string ' ABC ' and ' 123 ', you can use the two-storey village exchange, generate the full array
[N+m for M in ' ABC ' for n in ' 123 ']
Exercise: Use a three-layer nested for loop to find the symmetric 3-digit number such as 121
Print [100*m+10*n+m for M in range (1,10) for n in range (0,10)]
L=[]
For x in range (1,10):
For Y in range (10):
For z in range (1,10):
If X==z:
L.append (100*x+10*y+z)
Print L
Recommended courses:
Python online video tutorial