This article mainly describes the practical use of the python list generator! Hope to help beginners! 1. Complex list-based HTML table: This article mainly describes the practical application of the python list-based syntax! Hope to help beginners!
1. Complex list-based HTML table:
Note: the string can be formatted by %, and % s can be replaced by the specified parameterization. The join () method of a string can splice a list into a string.
Mark Few scores as red:
D = {'Adam ': 95, 'Lisa': 85, 'Bart': 59}
Def generate_tr (name, score ):
If score <60
Return'% S% S'% (Name, score)
Return'% S% S'% (Name, score)
Tds = [generate_tr (name, score) for name, score in d. iteritems ()]
Print'
'Print'
| Name |
Score |
'Print '\ n'. join (tds)Print'
'
2. conditional filtering
If judgment can be added after the for loop of the list generation type:
Returns all strings in the list in uppercase. non-string elements are ignored.
Tip:
1. isintance (x, str) can be used to determine whether the variable x is a string.
2. the string upper () method 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 expressions
The for loop can be nested. Therefore, you can use a multi-layer for loop to generate a list.
For example, for strings 'ABC' and '123', you can use two-layer village replacement to generate a full arrangement.
[N + m for m in 'abc' for n in '123']
Exercise: use a three-layer nested for loop to find the symmetric 3-digit, for example, 121
Print [100 * m + 10 * n + m for m in range () for n in range ()]
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
Course recommendations:
Python online video tutorial
The above is the details of the python complex list generative tutorial. For more information, see other related articles in the first PHP community!