# python列表生成式

python列表生成式

1. 生成列表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)]2. 复杂表达式d = { ‘adam’: 95, ‘lisa’: 85, ‘bart’: 59 }
tds = [‘%s%s’ % (name, score) for name, score in d.iteritems()]
print ”
print ‘namescore’
print ‘\n’.join(tds)
print ”
print ‘\n’
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 'namescore' print '\n'.join(tds) print ''3. 条件过滤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])4. 多层表达式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]

Posted in 未分类