Python入门篇-解析式、生成器
作者:尹正杰
版权声明:原创作品,谢绝转载!否则将追究法律责任。
一.列表解析式(List Comprehension)
1>.列表解析式语法
语法
[ 返回值 for 元素 in 可迭代对象 if 条件]
使用中括号[],内部是for循环,if条件语句可选
返回一个新的列表
列表解析式是一种语法糖
编译器会优化,不会因为简写而影响效率,反而因优化提高了效率
减少程序员工作量,减少出错
简化了代码,但可读性增强
2>.列表解析式案例
#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com """ 生成一个列表,元素0~9,对每一个元素自增1后求平方返回新列表 """ list_1 = list(range(10)) list_2 = [] for i in list_1: list_2.append((i+1)**2) print(list_2) print(type(list_2)) list_1 = list(range(10)) list_2 = [(i+1)**2 for i in list_1] print(list_2) print(type(list_2)) #以上代码执行结果如下 [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] <class 'list'> [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] <class 'list'>
3>.小试牛刀
#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com list_1 = [ x * x for x in range(1,11)] print(list_1) #以上代码执行结果如下: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]