Python——列表生成式

来源:互联网 发布:全民枪战挂机软件 编辑:程序博客网 时间:2024/04/29 23:53

生成列表

生成[1x1, 2x2, 3x3, …, 10x10],方法一:

>>> L = []>>> for x in range(1, 11):...    L.append(x * x)... >>> L[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

但是使用列表生成式,可以这样写:

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

一行搞定。

复杂表达式

d = { 'Adam': 95, 'Lisa': 85, 'Bart': 59 }def generate_tr(name, score):    if score<60 :        return '<tr><td style="color:red">%s</td><td>%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>'

条件过滤

例如:编写一个函数,它接受一个 list,然后把list中的所有字符串变成大写后返回,非字符串元素将被忽略

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

多层表达式

对于for循环,还可以嵌套使用:

#print [x for x in range(100,1000) if str(x)[0]==str(x)[-1]]L=[]for m in range(1,10):    for n in range(10):        for x in range(10):            if str(m)==str(x) :                L.append(m*100+n*10+x)print L
0 0
原创粉丝点击