py基础之列表生成式

列表生成式就是用一句语句生成一个列表,格式基本是:x for i in L
下面是使用for循环迭代dict而生成的一个复杂表达式,将输出后的字符串保存为html文档可以生成一个表格
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></tr>'
tds = [generate_tr(name, score) for name, score in d.items()]
print('<table>')
print('<tr><th>name</th><th>score</th><tr>')
print('\n'.join(tds))
print('</table>')
列表生成式的for循环后面还可以跟if进行条件过滤,格式是:x for i in L if true
isinstance(x,str)可以用来判断x是否为字符串
列表生成式也可以用for进行多层迭代,格式为:[a*b for a in L for b in L]
迭代是一种操作,在python中值得就是for循环
迭代还有索引迭代,因为有的时候我们需要拿出一个集合的索引
enumerate()可以将每个元素变成一个(index,element)的tuple
dict中的values()方法可以将dict中的value单独封装成一个list
dict中的keys()方法可以将dict中的key单独封装成一个list
dict中的ietms()方法可以将dict中的(key,value)封装成一个list方法
posted @ 2018-01-08 20:27  陌离殇  阅读(213)  评论(0编辑  收藏  举报