Home  >  Article  >  Backend Development  >  python complex list generation tutorial

python complex list generation tutorial

PHPz
PHPzOriginal
2017-04-23 16:56:501936browse

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 '%s%s< ;/tr>' % (name, score)
return '%s%s' % (name, score)
tds = [generate_tr(name, score) for name, score in d.iteritems()]
print '

'
print ''
print '\n'.join(tds)
print '
NameScore
'

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:

Python online video tutorial

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn