This article mainly explains the practical application examples of python list generation! Hope this helps beginners!
1. Complex list-generated HTML table:
Note: Strings can be formatted with %, and %s can be replaced with specified parameterization. The join() method of string can concatenate a list into a string.
Mark the few scores in red:
d = { 'Adam': 95, 'Lisa': 85, 'Bart': 59 }
def generate_tr(name , score):
if score < 60
return '
Name | Score |
---|---|
2. Conditional filtering
You can also add if judgment after the for loop of list generation:
Change all strings in the list to uppercase and return, non-string elements Will be ignored
Tips:
1. isintance(x,str) can determine whether the variable x is a string
2. The upper() method of the string can return Capital letters
def toUppers(L):
return [x.upper() for x in L if isinstance(x,str)]
print toUppers(['Hello', 'world', 101])
3. Multi-level expressions
For loops can be nested, so in list generation formulas, you can use multi-level for loops to generate lists
For example: for the strings 'ABC' and '123', you can use two-level village replacement to generate a full arrangement
[n+m for m in 'ABC' for n in '123']
Exercise: Use three levels of nested for loops to find symmetrical 3-digit numbers 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
Course recommendation:
The above is the detailed content of python complex list generation tutorial. For more information, please follow other related articles on the PHP Chinese website!