Python list generation

高洛峰
Release: 2017-02-17 11:10:14
Original
1424 people have browsed it

Python list generation

1. Generate list

L = []
for x in range(1, 11):
    L.append(x * x)
print L

print '\n'

print [x * x for x in range(1, 11)]

print '\n'

print [x * (x + 1) for x in range(1, 100, 2)]
Copy after login

2. Complex expression

d = { 'Adam': 95, 'Lisa': 85, 'Bart': 59 }
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>'

print '\n'

d = { 'Adam': 95, 'Lisa': 85, '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>'
Copy after login

3. Conditional filtering

print [x * x for x in range(1, 11)]

print '\n'

print [x * x for x in range(1, 11) if x % 2 == 0]

print '\n'

def toUppers(L):
    return [x.upper() for x in L if isinstance(x, str)]
print toUppers(['Hello', 'world', 101])
Copy after login

4. More Layer expression

print [m + n for m in 'ABC' for n in '123']

print '\n'

L = []
for m in 'ABC':
    for n in '123':
        L.append(m + n)
print L

print '\n'

print [100 * n1 + 10 * n2 + n3 for n1 in range(1, 10) for n2 in range(10) for n3 in range(10) if n1==n3]
Copy after login

For more Python list generation related articles, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!