【脚本语言系列】关于Python基础知识推导式,你需要知道的事
2017-07-20 16:10
816 查看
如何使用推导式(Comprehension)
列表(list)推导式var_list = [ out_element for out_element in in_list if out_element judge sth]
# -*- coding:utf-8 -*- div_list = [element for element in range(25) if element % 4 is 0] print div_list
[0, 4, 8, 12, 16, 20, 24]
# -*- coding:utf-8 -*- pow2_list = [] for x in range(25): pow2_list.append(x**2) print pow2_list pow2_list = [x**2 for x in range(25)] print pow2_list pow3_list = [] for x in range(25): pow3_list.append(x**3) print pow3_list pow3_list = [x**3 for x in range(25)] print pow3_list
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400, 441, 484, 529, 576] [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400, 441, 484, 529, 576] [0, 1, 8, 27, 64, 125, 216, 343, 512, 729, 1000, 1331, 1728, 2197, 2744, 3375, 4096, 4913, 5832, 6859, 8000, 9261, 10648, 12167, 13824] [0, 1, 8, 27, 64, 125, 216, 343, 512, 729, 1000, 1331, 1728, 2197, 2744, 3375, 4096, 4913, 5832, 6859, 8000, 9261, 10648, 12167, 13824]
字典(dict)推导式
var_dict = { key_element:value_elements for key_element in key_list}
# -*- coding:utf-8 -*- class_freq_dict = {"a":12, "b":23, "A":34, "B":45} noclass_freq_dict = {key.lower(): class_freq_dict.get(key.lower(),0)+class_freq_dict.get(key.upper(),0)for key in class_freq_dict.keys()} print noclass_freq_dict
{'a': 46, 'b': 68}
# -*- coding:utf-8 -*- class_freq_dict = {"a":12, "b":23, "A":34, "B":45} swap_dict = {value: key for key, value in class_freq_dict.items()} print swap_dict
{34: 'A', 12: 'a', 45: 'B', 23: 'b'}
集合(set)推导式
var_set = { out_element for out_element in in_set if out_element judge sth}
# -*- coding:utf-8 -*- pow2_set = {x**2 for x in range(25)} print pow2_set pow3_set = {x**3 for x in range(25)} print pow3_set
set([0, 1, 4, 9, 256, 144, 529, 25, 576, 196, 289, 36, 169, 49, 441, 64, 324, 81, 484, 225, 100, 16, 361, 400, 121]) set([0, 1, 4096, 12167, 8, 2197, 512, 10648, 27, 8000, 9261, 3375, 4913, 1331, 13824, 2744, 1728, 64, 5832, 6859, 343, 216, 729, 1000, 125])
什么是推导式(Comprehension)
推导式(解析式)是从一个数据序列构建另一个新的数据序列的结构体。共有3种推导:
* 列表推导式
* 字典推导式
* 集合推导式
相关文章推荐
- 【脚本语言系列】关于Python基础知识协程,你需要知道的事
- 【脚本语言系列】关于Python基础知识枚举,你需要知道的事
- 【脚本语言系列】关于Python基础知识迭代器,你需要知道的事
- 【脚本语言系列】关于Python基础知识__slots__,你需要知道的事
- 【脚本语言系列】关于Python基础知识异常处理,你需要知道的事
- 【脚本语言系列】关于Python基础知识调试,你需要知道的事
- 【脚本语言系列】关于Python基础知识映射器和过滤器,你需要知道的事
- 【脚本语言系列】关于Python基础知识兼容Python 2.x+Python 3.x,你需要知道的事
- 【脚本语言系列】关于Python基础知识面向对象编程,你需要知道的事
- 【脚本语言系列】关于Python基础知识处理字符串,你需要知道的事
- 【脚本语言系列】关于Python基础知识函数缓存,你需要知道的事
- 【脚本语言系列】关于Python基础知识装饰器,你需要知道的事
- 【脚本语言系列】关于Python基础知识对象自省,你需要知道的事
- 【脚本语言系列】关于Python基础知识Lambda表达式,你需要知道的事
- 【脚本语言系列】关于Python基础知识魔法变量,你需要知道的事
- 【脚本语言系列】关于Python基础知识文件操作,你需要知道的事
- 【脚本语言系列】关于Python基础知识设计模式,你需要知道的事
- 【脚本语言系列】关于Python基础知识容器,你需要知道的事
- 【脚本语言系列】关于Python基础知识多返回值,你需要知道的事
- 【脚本语言系列】关于Python基础知识对象变动,你知道的事